.NET 帮助

FileStream C#(面向开发人员的工作原理)

发布 2024年十月24日
分享:

本文将重点介绍文件流类C# 中的".NET "和".NET",以及它如何帮助您对文件执行读写操作。 我们将探讨实际示例,了解 FileStream 的核心工作原理,并学习如何有效管理文件数据。 本指南针对的是那些刚刚接触 C# 文件处理的人,因此语言将保持初学者友好的风格,同时提供用 C# 处理文件的详细说明以及对IronPDF 库以及。

什么是 FileStream?

C# 中的 FileStream 类提供了一种使用字节处理文件的方法。 它可以对文件进行读写操作,允许您直接与文件内容进行交互。 在使用文件进行输入/输出任务时,尤其是在操作字节数组时,这一点尤其有用。

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
VB   C#

本示例演示创建 FileStream 对象以处理文件读写操作。 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
VB   C#

在这段代码中,我们使用 UTF8 编码将字符串转换为字节数组。 Write 方法从当前位置开始将字节数组写入文件(由偏移量决定)并写入指定的字节数。

  • FileMode.Create 会创建一个新文件,覆盖同名的任何现有文件。
  • FileAccess.Write 赋予 FileStream 写入权限。

使用 FileStream 读取数据

现在,让我们来探讨如何使用 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
VB   C#

在此示例中:

  • FileMode.Open 打开现有文件。
  • 读取方法读取指定数量的字节(基于缓冲区大小)并将其存储在字节数组缓冲区中。
  • 我们使用 Encoding.UTF8.GetString 将字节数据转换回字符串。

使用 FileStream 管理文件访问

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
VB   C#

使用 FileStream 进行异步操作

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
VB   C#

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
VB   C#

缓冲和性能

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
VB   C#

在这里,FileOptions.WriteThrough 可确保数据直接写入文件,绕过额外的缓冲。 不过,您可以控制缓冲区的大小,以便进行性能调整。

介绍IronPDF

FileStream C#(如何为开发人员工作):图 1 - IronPDF:C# PDF 库

IronPDFC# PDF 是一个强大的 C# PDF 库,用于在 .NET 应用程序中创建、编辑和操作 PDF 文档。 开发人员可以从 HTML 等各种输入生成 PDF使用 IronPDF,您可以将文档、图像、甚至原始文本翻译成各种格式。 IronPDF 具有水印、合并、分割和密码保护等功能,是网络和桌面应用程序精确控制 PDF 输出的理想选择。

IronPDF 与 FileStream

下面是一个使用 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
VB   C#

结论

FileStream C#(如何为开发人员工作):图 2 - IronPDF 许可页面

C# 中的 FileStream 类提供了管理文件输入和输出的强大功能。 通过了解字节数组、文件路径和流处理如何协同工作,开发人员可以高效地读写数据、控制文件中的当前位置以及异步工作。 将 FileStream 与 IronPDF 结合使用可为开发人员提供在 .NET 应用程序中高效处理 PDF 的灵活性。 无论是生成报告、保存文件还是处理动态内容,这一组合都能为创建和存储 PDF 文档提供精细的控制。

IronPDF 提供一个免费试用以及 749 美元的 License 费用,使其成为满足专业 PDF 生成需求的具有竞争力的解决方案。

< 前一页
C# 初始化列表(如何为开发人员工作)
下一步 >
C# Init 关键字(如何为开发人员工作)

准备开始了吗? 版本: 2024.12 刚刚发布

免费NuGet下载 总下载量: 11,622,374 查看许可证 >