.NET 帮助 FileStream C#(开发者用法) Curtis Chau 已更新:七月 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 简介 ! FileStream C#(开发人员如何运作):图1 - IronPDF:C# PDF库 IronPDF是一个强大的C# PDF库,用于在.NET应用程序中创建、编辑和操作PDF文件。 开发人员可以使用IronPDF从HTML、图像甚至原始文本等多种输入生成PDF。 凭借水印、合并、拆分和密码保护等功能,IronPDF是能够精确控制PDF输出的Web和桌面应用程序的理想选择。 结合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 结论 ! FileStream C#(开发人员如何运作):图2 - IronPDF许可页面 C#中的FileStream类为管理文件输入和输出提供了强大的功能。 它允许开发人员高效地读写数据,控制文件中的当前位置,并通过了解字节数组、文件路径和流处理的协同工作来进行异步操作。 将FileStream与IronPDF结合使用,为开发人员提供在.NET应用程序内高效处理PDF的灵活性。 无论您是生成报告、保存文件,还是处理动态内容,这种组合都提供了对PDF文档创建和存储的精确控制。 IronPDF提供免费试用并收取$799许可费,使其成为满足专业PDF生成需求的竞争解决方案。 常见问题解答 如何在 C# 中执行文件的读写操作? 您可以使用 FileStream 类在 C# 中执行文件的读写操作。它允许您打开文件并使用 Read 和 Write 等方法来高效地处理文件数据。 使用 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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# Switch 模式匹配(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# 初始化列表(开发者用法)C# Init 关键字(开发者用法)
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多