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
此範例演示了建立一個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
在這段程式碼中,我們使用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
在這個範例中:
- FileMode.Open 打開一個現有檔案。
- Read方法根據緩衝區大小讀取指定數量的位元組,並將其儲存在位元組陣列緩衝區中。
- 我們使用
Encoding.UTF8.GetString將位元組資料轉換回字串。
使用FileStream管理檔案存取
FileStream類別控制文件的存取,允許對文件控制權和系統資源進行精細調整。 使用FileStream時,確保流在使用後正確處置至關重要,可以手動調用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
使用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
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}");
}
}
}
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
緩衝和性能
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
在這裡,FileOptions.WriteThrough確保資料直接寫入至文件,繞過額外的緩衝。 不過,您可以控制緩衝區大小以進行性能調整。
介紹 IronPDF

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.");
}
}
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
結論

C#中的FileStream類別為管理文件的輸入與輸出提供了強大的功能。 它允許開發者有效地讀寫資料,控制文件中的當前位置,並通過理解位元組陣列、文件路徑和流處理的工作原理來進行異步工作。 將FileStream與IronPDF結合使用,為開發者提供了靈活性,以高效地在.NET應用程式中處理PDF。 無論您是在生成報告、保存檔案還是處理動態內容,此組合都能對PDF文件的建立和儲存提供精細的控制。
IronPDF提供免費試用和$999授權費用,使其成為專業PDF生成需求的競爭解決方案。
常見問題
我如何在C#中對文件執行讀寫操作?
您可以使用FileStream類在C#中對文件執行讀寫操作。它允許您開檔案,使用如Read和Write的方法來有效處理文件資料。
使用FileStream處理C#中的文件有哪些好處?
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管理的綜合工具。




