.NET幫助 FileStream C#(對開發者如何理解的工作) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 這篇文章將重點介紹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.Read和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}"); } } } 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 IronPDF是一個強大的C# PDF庫,可在.NET應用程序中創建、編輯和操作PDF文檔。 開發者可以使用IronPDF從各種輸入如HTML、圖片甚至原始文本生成PDF。 具有水印、合併、分割和密碼保護等功能,IronPDF非常適用於需要精確控制PDF輸出的網頁和桌面應用程序。 FileStream與IronPDF 這裡是一個利用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 結論 C#中的FileStream類提供了用於管理文件輸入和輸出的強大功能。 它允許開發者有效地讀取和寫入數據,控制文件中的當前位置,並通過理解位元組陣列、文件路徑和流處理如何協同工作來進行異步操作。 將FileStream與IronPDF結合使用,為開發者提供了在.NET應用程序中高效處理PDF的靈活性。 無論您是在生成報告、保存文件還是處理動態內容,這種組合都提供了對創建和儲存PDF文檔的精確控制。 IronPDF提供免費試用版和$799許可費,這使其成為專業PDF生成需求的競爭解決方案。 常見問題解答 我如何在C#中進行文件讀寫操作? 您可以使用FileStream類別在C#中進行文件讀寫操作。它允許您打開文件並使用像Read和Write這樣的方法來高效地處理文件數據。 在C#中使用FileStream進行文件處理有什麼好處? FileStream對於處理二進位數據、管理大文件和高效地執行非同步文件操作非常有益。它優化內存使用並允許對文件數據處理進行精確控制。 FileStream如何處理大文件? FileStream通過使用緩衝來處理大文件,這會在內存中暫時存儲數據以最小化磁碟訪問。這提升了性能並使FileStream適合處理大文件。 FileStream可用於非同步文件操作嗎? 是的,FileStream支持非同步文件操作。您可以使用像ReadAsync和WriteAsync這樣的方法來提高應用程式性能,允許同時處理。 為什麼正確處置FileStream對象很重要? 正確處置FileStream對象對於釋放系統資源和防止文件鎖定至關重要。您可以使用using語句或調用Dispose方法來確保資源得到正確釋放。 如何在C#中整合PDF生成與文件處理? 您可以使用IronPDF在C#中整合PDF生成與文件處理。IronPDF允許您創建和操作PDF文檔,並使用FileStream保存它們,無縫結合文件處理和PDF創建。 IronPDF在PDF操作上有哪些功能? IronPDF提供創建、編輯和操作PDF功能,增加水印、合併文檔、拆分文件和應用密碼保護,使其成為.NET應用程式中全方位的PDF管理工具。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C#初始化列表(對開發者如何理解的工作)C#初始化關鍵字(對開發者...