跳過到頁腳內容
.NET幫助

FileStream 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);
        }
    }
}
Imports System
Imports System.IO

Public Class Example
	Public Shared Sub Main()
		Dim path As String = "example.txt"

		' Creating a FileStream object to handle the file. The file handle is acquired here.
		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
			Dim data() As Byte = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!")
			' Write data to file
			fileStream.Write(data, 0, data.Length)
		End Using

		' Read from the file
		Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
			Dim buffer(1023) As Byte
			Dim bytesRead As Integer = fileStream.Read(buffer, 0, buffer.Length)
			Dim text As String = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)
			Console.WriteLine(text)
		End Using
	End Sub
End Class
$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);
        }
    }
}
Imports System
Imports System.IO

Public Class FileWriteExample
	Public Shared Sub Main()
		Dim path As String = "output.txt"

		' Creating a FileStream object to write data to the file
		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
			Dim buffer() As Byte = System.Text.Encoding.UTF8.GetBytes("Writing data to FileStream.")
			Dim offset As Integer = 0
			Dim count As Integer = buffer.Length

			' Writing data to the file
			fileStream.Write(buffer, offset, count)
		End Using
	End Sub
End Class
$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);
        }
    }
}
Imports System
Imports System.IO

Public Class FileReadExample
	Public Shared Sub Main()
		' File path
		Dim path As String = "output.txt"

		' File Stream Object
		Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
			Dim buffer(1023) As Byte
			Dim bytesRead As Integer = fileStream.Read(buffer, 0, buffer.Length)
			' Output Stream
			Dim output As String = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)
			Console.WriteLine(output)
		End Using
	End Sub
End Class
$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
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);
        }
    }
}
Imports System
Imports System.IO
Imports System.Threading.Tasks

Public Class AsyncReadExample
	Public Shared Async Function Main() As Task
		' Specified Path
		Dim path As String = "output.txt"

		Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, True)
			Dim buffer(1023) As Byte
			Dim bytesRead As Integer = Await fileStream.ReadAsync(buffer, 0, buffer.Length)
			Dim result As String = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)
			Console.WriteLine(result)
		End Using
	End Function
End Class
$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}");
        }
    }
}
Imports System
Imports System.IO

Public Class ExceptionHandlingExample
	Public Shared Sub Main()
		Dim path As String = "nonexistentfile.txt"

		Try
			Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
				Dim buffer(1023) As Byte
				Dim bytesRead As Integer = fileStream.Read(buffer, 0, buffer.Length)
				Console.WriteLine("Bytes Read: " & bytesRead)
			End Using
		Catch e As FileNotFoundException
			Console.WriteLine($"Exception: {e.Message}")
		End Try
	End Sub
End Class
$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);
        }
    }
}
Imports System
Imports System.IO

Public Class BufferingExample
	Public Shared Sub Main()
		Dim path As String = "bufferedfile.txt"
		Dim data() As Byte = System.Text.Encoding.UTF8.GetBytes("Buffered FileStream example.")

		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)
			fileStream.Write(data, 0, data.Length)
		End Using
	End Sub
End Class
$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.");
    }
}
Imports System
Imports System.IO
Imports IronPdf

Public Class IronPDFExample
	Public Shared Sub Main()
		' Define the file path
		Dim path As String = "output.pdf"

		' Create an HTML string that we want to convert to PDF
		Dim 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
		Dim renderer = New ChromePdfRenderer()

		' Generate the PDF from the HTML string
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

		' Use FileStream to save the generated PDF
		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
			pdfDocument.SaveAs(fileStream)
		End Using

		Console.WriteLine("PDF created and saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

結論

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

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

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

常見問題解答

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

您可以使用FileStream類別在C#中進行文件讀寫操作。它允許您打開文件並使用像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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我