在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
本文將重點介紹FileStream 類別在 C# 中,它如何幫助您進行文件的讀寫操作。 我們將探討實際範例,了解 FileStream 的基本運作方式,並學習如何有效管理檔案資料。 本指南適合剛開始學習 C# 檔案處理的新手,因此語言將保持初學者友好,同時提供有關在 C# 中處理檔案的詳細說明和介紹。IronPDF 庫以及。
C# 中的 FileStream 類提供了一種使用位元組處理檔案的方法。 它適用於文件的讀寫操作,使您能夠直接與文件內容互動。 這在處理輸入/輸出任務的文件時特別有用,尤其是在操作位元組陣列時。
FileStream 適用於:
以下是一個使用 FileStream 開啟檔案、寫入資料,然後讀取的簡單範例:
using System;
using System.IO;
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!");
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 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!");
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 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!")
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
此範例展示了如何創建一個 FileStream 物件來處理檔案讀寫操作。 FileStream 類別直接讀取和寫入位元組,適合處理大型檔案或二進位資料。 我們使用編碼在文本和字節之間進行轉換。
要將資料寫入檔案,您將使用 Write 方法。 以下是更詳細說明其工作原理的示例:
using System;
using System.IO;
public static void Main()
{
string path = "output.txt";
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 static void Main()
{
string path = "output.txt";
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 Shared Sub Main()
Dim path As String = "output.txt"
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
在這段程式碼中,我們使用 UTF8 編碼將字串轉換為位元組陣列。 Write 方法從當前位置開始將字節陣列寫入文件。(由偏移量決定)寫入指定數量的位元組。
現在,我們來探索如何使用 FileStream 從檔案讀取資料。
using System;
using System.IO;
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 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 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
在此範例中:
FileStream 類別控制檔案的存取,允許精細調整的檔案控制和系統資源管理。 使用 FileStream 時,確保在使用後正確處理流非常重要,可以通過調用 Close 來完成。()手動處理或使用自動釋放流的語句。
每次讀取或寫入文件時,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 可以用於非同步讀寫操作,透過允許其他程序在文件操作執行時運行來提升性能。 以下是一個非同步讀取的基本範例:
using System;
using System.IO;
using System.Threading.Tasks;
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 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 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
ReadAsync 方法异步地读取数据。 FileAccess.Read
和 FileMode.Open
參數控制檔案的存取方式。
在使用FileStream時,處理異常是至關重要的,以避免運行時錯誤並正確管理系統資源。 以下是讀取或寫入檔案時處理異常的模式:
using System;
using System.IO;
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 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 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
FileStream 類別包含緩衝機制,使效能更快,特別是在處理大型檔案時。 使用緩衝區,數據臨時存儲在記憶體中,減少對磁碟的不斷訪問需求。
using System;
using System.IO;
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 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 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
在這裡,FileOptions.WriteThrough 確保數據直接寫入文件,繞過額外的緩衝。 然而,您可以控制緩衝區大小以進行性能調整。
IronPDF是一個強大的 C# PDF 函式庫,用於在 .NET 應用程式中建立、編輯和操作 PDF 文件。 開發人員可以從各種輸入(如HTML)生成PDF檔案、圖像,甚至使用 IronPDF 的原始文本。 IronPDF 提供浮水印、合併、分割和密碼保護等功能,非常適合對 PDF 輸出有精確控制的網頁和桌面應用程式。
以下是使用 IronPDF 生成 PDF 並將其保存到 FileStream 的範例。 這展示了IronPDF如何順利整合FileStream,讓開發人員能夠以程式方式控制PDF的創建和保存。
using System;
using System.IO;
using IronPdf;
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 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 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
C# 中的 FileStream 類別提供強大的功能來管理文件的輸入和輸出。 它允許開發人員高效讀寫數據,控制文件中的當前位置,並通過理解位元組數組、文件路徑和流處理如何相互協作來進行非同步工作。 將 FileStream 與 IronPDF 結合使用能夠為開發者提供在 .NET 應用程式中高效處理 PDF 的彈性。 無論是生成報告、保存文件,還是處理動態內容,這種組合在創建和存儲 PDF 文件方面提供了精細控制。
IronPDF 提供一個免費試用以及 749 美元的授權費,使其成為滿足專業 PDF 生成需求的一個具有競爭力的解決方案。