IRONSOFTWAREHOME
開發者更新

FileStream C# (如何為開發人員運作)

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月23日

本文將專注於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);
        }
    }
}

此範例演示了建立一個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);
        }
    }
}

在這段程式碼中,我們使用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);
        }
    }
}

在這個範例中:

  • FileMode.Open 打開一個現有檔案。
  • Read方法根據緩衝區大小讀取指定數量的位元組,並將其儲存在位元組陣列緩衝區中。
  • 我們使用Encoding.UTF8.GetString將位元組資料轉換回字串。

使用FileStream管理檔案存取

FileStream類別控制文件的存取,允許對文件控制權和系統資源進行精細調整。 使用FileStream時,確保流在使用後正確處置至關重要,可以手動調用using語句。

處理檔案位置

每次對檔案進行讀取或寫入操作時,FileStream會跟蹤文件中的當前位置。您可以使用Position屬性存取此位置:

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

使用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);
        }
    }
}

ReadAsync方法異步讀取資料。 FileMode.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}");
        }
    }
}

緩衝和性能

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);
        }
    }
}

在這裡,FileOptions.WriteThrough確保資料直接寫入至文件,繞過額外的緩衝。 不過,您可以控制緩衝區大小以進行性能調整。

介紹 IronPDF

FileStream C#(對開發者的運作):圖1 - IronPDF:C# PDF Library

IronPDF是一個強大的C# PDF程式庫,用於在.NET應用程式中建立、編輯和操作PDF文件。 開發者可以使用IronPDF從各種輸入中生成PDF,如HTML、圖像,甚至是原始文字。 IronPDF具有如浮水印、合併、分割和密碼保護等功能,對於需要準確控制PDF輸出的網路和桌面應用程式非常理想。

IronPDF with 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.");
    }
}

結論

C#中的FileStream類別為管理文件的輸入與輸出提供了強大的功能。 它允許開發者有效地讀寫資料,控制文件中的當前位置,並通過理解位元組陣列、文件路徑和流處理的工作原理來進行異步工作。 將FileStream與IronPDF結合使用,為開發者提供了靈活性,以高效地在.NET應用程式中處理PDF。 無論您是在生成報告、保存檔案還是處理動態內容,此組合都能對PDF文件的建立和儲存提供精細的控制。

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

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰。

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密。
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰。
無需信用卡或帳戶建立
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999起