跳至頁尾內容
.NET 幫助

C# 檔案流(開發者使用方法)

本文將重點介紹 C# 中的 FileStream 類,以及它如何協助您執行檔案的讀寫作業。 我們將探討實際範例,瞭解 FileStream 的核心運作方式,並學習如何有效管理檔案資料。 本指南針對的是那些剛開始使用 C# 處理檔案的人,因此語言將保持初學者的親和力,同時提供使用 C# 處理檔案的詳細說明,以及 IronPDF 函式庫的介紹

什麼是 FileStream?

C# 中的 FileStream 類提供了一種使用位元組來處理檔案的方法。 它的工作原理是對檔案進行讀寫操作,讓您可以直接與檔案內容互動。 這在處理輸入/輸出任務的檔案時特別有用,尤其是在操作位元組陣列的時候。

FileStream 使用案例

FileStream 是下列人士的理想選擇

  • 直接從檔案讀取或寫入二進位資料。
  • 有效率地處理大型檔案。
  • 執行異步檔案作業。
  • 透過有效使用記憶體來管理系統資源。

基本範例

以下是一個簡單的範例,使用 FileStream 開啟檔案、寫入資料,然後讀取:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = "example.txt";

        // Creating a FileStream object to handle the file. The file handle is acquired here.
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");
            // Write data to file
            fileStream.Write(data, 0, data.Length);
        }

        // Read from the file
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            string text = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(text);
        }
    }
}
using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = "example.txt";

        // Creating a FileStream object to handle the file. The file handle is acquired here.
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");
            // Write data to file
            fileStream.Write(data, 0, data.Length);
        }

        // Read from the file
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            string text = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(text);
        }
    }
}
$vbLabelText   $csharpLabel

本範例示範建立 FileStream 物件,以處理檔案讀寫作業。 FileStream 類別可直接讀寫位元組,因此適合處理大型檔案或二進位資料。 我們使用 Encoding 在文字和位元組之間進行轉換。

使用 FileStream 寫入資料。

若要將資料寫入檔案,您將使用 Write 方法。 以下是一個範例,可以更詳細地說明如何運作:

using System;
using System.IO;

public class FileWriteExample
{
    public static void Main()
    {
        string path = "output.txt";

        // Creating a FileStream object to write data to the file
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Writing data to FileStream.");
            int offset = 0;
            int count = buffer.Length;

            // Writing data to the file
            fileStream.Write(buffer, offset, count);
        }
    }
}
using System;
using System.IO;

public class FileWriteExample
{
    public static void Main()
    {
        string path = "output.txt";

        // Creating a FileStream object to write data to the file
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Writing data to FileStream.");
            int offset = 0;
            int count = buffer.Length;

            // Writing data to the file
            fileStream.Write(buffer, offset, count);
        }
    }
}
$vbLabelText   $csharpLabel

在此程式碼中,我們使用 UTF8 編碼將字串轉換為位元組陣列。 Write 方法會從目前位置 (由偏移量決定) 開始寫入位元組到檔案,並寫入指定的位元組數量。

  • FileMode.Create 會建立新檔案,並覆寫任何具有相同名稱的現有檔案。
  • FileAccess.Write 授予 FileStream 的寫入權限。

使用 FileStream 讀取資料。

現在,讓我們探索如何使用 FileStream 從檔案讀取資料。

using System;
using System.IO;

public class FileReadExample
{
    public static void Main()
    {
        // File path
        string path = "output.txt";

        // File Stream Object
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            // Output Stream
            string output = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(output);
        }
    }
}
using System;
using System.IO;

public class FileReadExample
{
    public static void Main()
    {
        // File path
        string path = "output.txt";

        // File Stream Object
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            // Output Stream
            string output = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(output);
        }
    }
}
$vbLabelText   $csharpLabel

在這個範例中

  • FileMode.Open 開啟現有檔案。
  • Read 方法讀取指定數量的位元組(基於緩衝區大小)並將其儲存到位元組緩衝區中。
  • 我們使用 Encoding.UTF8.GetString 將位元組資料轉換回字串。

使用 FileStream 管理檔案存取。

FileStream 類別可控制檔案存取,允許微調檔案句柄和系統資源管理。 在使用 FileStream 時,確保在使用後適當地處理流是非常重要的,可以手動呼叫 Close() 或使用 using 語句來自動處理流。

處理檔案位置

每次讀取或寫入檔案時,FileStream 都會追蹤檔案中的目前位置。您可以使用 Position 屬性存取此位置:

fileStream.Position = 0; // Move to the beginning of the file
fileStream.Position = 0; // Move to the beginning of the file
$vbLabelText   $csharpLabel

使用 FileStream 進行異步操作。

FileStream 可用於異步讀取和寫入作業,可在執行檔案作業時允許其他程序執行,從而改善效能。 以下是異步閱讀的基本範例:

using System;
using System.IO;
using System.Threading.Tasks;

public class AsyncReadExample
{
    public static async Task Main()
    {
        // Specified Path
        string path = "output.txt";

        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, true))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length);
            string result = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(result);
        }
    }
}
using System;
using System.IO;
using System.Threading.Tasks;

public class AsyncReadExample
{
    public static async Task Main()
    {
        // Specified Path
        string path = "output.txt";

        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, true))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length);
            string result = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(result);
        }
    }
}
$vbLabelText   $csharpLabel

ReadAsync 方法以異步方式讀取資料。 FileAccess.ReadFileMode.Open 參數控制檔案的存取方式。

處理異常的範例

在使用 FileStream 工作時,處理異常對於避免執行時錯誤和正確管理系統資源是非常重要的。 以下是讀取或寫入檔案時處理異常的模式:

using System;
using System.IO;

public class ExceptionHandlingExample
{
    public static void Main()
    {
        string path = "nonexistentfile.txt";

        try
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[1024];
                int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                Console.WriteLine("Bytes Read: " + bytesRead);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"Exception: {e.Message}");
        }
    }
}
using System;
using System.IO;

public class ExceptionHandlingExample
{
    public static void Main()
    {
        string path = "nonexistentfile.txt";

        try
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[1024];
                int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                Console.WriteLine("Bytes Read: " + bytesRead);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"Exception: {e.Message}");
        }
    }
}
$vbLabelText   $csharpLabel

緩衝與效能

FileStream 類別包含一個緩衝機制,可加快效能,尤其是在處理大型檔案時。 使用緩衝區,資料可暫存於記憶體中,減少不斷存取磁碟的需求。

using System;
using System.IO;

public class BufferingExample
{
    public static void Main()
    {
        string path = "bufferedfile.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Buffered FileStream example.");

        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
        {
            fileStream.Write(data, 0, data.Length);
        }
    }
}
using System;
using System.IO;

public class BufferingExample
{
    public static void Main()
    {
        string path = "bufferedfile.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Buffered FileStream example.");

        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
        {
            fileStream.Write(data, 0, data.Length);
        }
    }
}
$vbLabelText   $csharpLabel

在此,FileOptions.WriteThrough 可確保資料直接寫入檔案,繞過額外的緩衝。 不過,您可以控制緩衝區大小,以便進行效能調整。

介紹 IronPDF。

FileStream C# (How It Works For Developers):圖 1 - IronPDF:C# PDF 函式庫

IronPDF 是一個強大的 C# PDF 函式庫,用於在 .NET 應用程式中建立、編輯和處理 PDF 文件。 開發人員可以 使用 IronPDF 從 HTML、圖像甚至原始文字等各種輸入內容生成 PDF。 IronPDF 具備水印、合併、分割和密碼保護等功能,是精確控制 PDF 輸出的網頁和桌面應用程式的理想選擇。

IronPDF 與 FileStream

以下是使用 IronPDF 生成 PDF 并将其保存到 FileStream 的示例。 這展示了 IronPDF 如何與 FileStream 順利整合,讓開發人員可以程式化地控制 PDF 的建立與儲存。

using System;
using System.IO;
using IronPdf;

public class IronPDFExample
{
    public static void Main()
    {
        // Define the file path
        string path = "output.pdf";

        // Create an HTML string that we want to convert to PDF
        var htmlContent = "<h1>IronPDF Example</h1><p>This PDF was generated using IronPDF and saved with FileStream.</p>";

        // Initialize IronPDF's ChromePdfRenderer to render HTML as PDF
        var renderer = new ChromePdfRenderer();

        // Generate the PDF from the HTML string
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Use FileStream to save the generated PDF
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            pdfDocument.SaveAs(fileStream);
        }

        Console.WriteLine("PDF created and saved successfully.");
    }
}
using System;
using System.IO;
using IronPdf;

public class IronPDFExample
{
    public static void Main()
    {
        // Define the file path
        string path = "output.pdf";

        // Create an HTML string that we want to convert to PDF
        var htmlContent = "<h1>IronPDF Example</h1><p>This PDF was generated using IronPDF and saved with FileStream.</p>";

        // Initialize IronPDF's ChromePdfRenderer to render HTML as PDF
        var renderer = new ChromePdfRenderer();

        // Generate the PDF from the HTML string
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Use FileStream to save the generated PDF
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            pdfDocument.SaveAs(fileStream);
        }

        Console.WriteLine("PDF created and saved successfully.");
    }
}
$vbLabelText   $csharpLabel

結論

FileStream C# (How It Works For Developers):圖 2 - IronPDF 授權頁面

C# 中的 FileStream 類提供管理檔案輸入和輸出的強大功能。 它能讓開發人員有效率地讀取和寫入資料、控制檔案中的目前位置,並透過了解位元組陣列、檔案路徑和串流處理如何一起運作來進行異步工作。 將 FileStream 與 IronPDF 結合使用,可讓開發人員在 .NET 應用程式中靈活有效地處理 PDF。 無論您是要產生報表、儲存檔案或處理動態內容,這個組合都能提供精細的控制來建立和儲存 PDF 文件。

IronPDF 提供 免費試用和 $799 授權費用,使其成為滿足專業 PDF 生成需求的極具競爭力的解決方案。

常見問題解答

如何在C#中對文件進行讀寫操作?

在 C# 中,您可以使用FileStream類別對檔案執行讀寫操作。它允許您開啟檔案並使用ReadWrite等方法高效地處理檔案資料。

在 C# 中使用 FileStream 進行檔案處理有哪些好處?

FileStream 有利於處理二進位資料、管理大型檔案以及有效率地執行非同步檔案操作。它優化了記憶體使用,並允許對檔案資料處理進行精確控制。

FileStream 如何處理大檔案?

FileStream 透過緩衝技術處理大型文件,該技術會將資料暫時儲存在記憶體中,從而最大限度地減少磁碟存取。這提高了效能,使 FileStream 非常適合處理大型檔案。

FileStream 可以用於非同步檔案操作嗎?

是的,FileStream 支援非同步檔案操作。您可以使用ReadAsyncWriteAsync等方法,透過允許並發處理來提升應用程式效能。

為什麼正確釋放 FileStream 物件很重要?

正確釋放 FileStream 物件對於釋放系統資源和防止檔案鎖定至關重要。您可以使用using語句或呼叫Dispose方法來確保資源正確釋放。

如何在C#中將PDF生成與文件處理整合起來?

您可以使用 IronPDF 將 C# 中的 PDF 產生與文件處理整合起來。 IronPDF 可讓您建立和操作 PDF 文檔,並使用FileStream儲存它們,從而將文件處理和 PDF 建立無縫結合。

IronPDF在PDF處理上有哪些功能?

IronPDF 提供建立、編輯和操作 PDF、新增浮水印、合併文件、分割文件和應用密碼保護等功能,使其成為 .NET 應用程式中 PDF 管理的綜合工具。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。