IRONSOFTWAREHOME
开发者更新

FileStream C#(开发者用法)

Jacob Mellor,Team Iron 的首席技术官
Jacob Mellor
Updated: 2026年4月23日

本文将重点介绍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);
        }
    }
}

此示例展示了创建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);
        }
    }
}

在这段代码中,我们使用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);
        }
    }
}

在此示例中:

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

使用FileStream管理文件访问

FileStream类控制文件的访问,允许精细调整的文件句柄和系统资源管理。 使用FileStream时,确保在使用后正确释放流非常重要,可以手动调用using语句。

处理文件位置

每次您读或写文件时,FileStream都会跟踪文件中的当前位置。您可以使用Position属性访问此位置:

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);
        }
    }
}

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

缓冲和性能

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);
        }
    }
}

这里,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.");
    }
}

结论

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

IronPDF提供免费试用和$999许可费,使其成为专业PDF生成需求的具有竞争力的解决方案。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥。

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

OR
bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥。
无需信用卡或创建账户
C# 用于 PDF 的 NuGet 库
通过 NuGet 安装

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解决方案资源管理器中,右键点击引用,管理 NuGet 包
  2. 选择浏览并搜索 “IronPDF”
  3. 选择包并安装
C# PDF DLL
下载 DLL

版本: 2026.9

或在此处下载 Windows 安装程序。

  1. 下载并解压 IronPDF 到您的解决方案目录中的 ~/Libs 之类的位置
  2. 在 Visual Studio 解决方案资源管理器中,右键点击引用。选择浏览,“IronPDF.dll”

$999 起