当前位置: 首页 > article >正文

C# 文件 I/O 操作详解:从基础到高级应用

在软件开发中,文件操作(I/O)是一项基本且重要的功能。无论是读取配置文件、存储用户数据,还是处理日志文件,C# 都提供了丰富的 API 来高效地进行文件读写操作。本文将全面介绍 C# 中的文件 I/O 操作,涵盖基础文件操作、文本/二进制文件读写、流式处理、异步 I/O 以及最佳实践,帮助开发者掌握文件处理的技巧。

1. C# 文件操作基础

C# 的文件操作主要依赖于 System.IO 命名空间,其中 FileDirectoryStreamReaderStreamWriter 等类是核心工具。

1.1 检查文件是否存在

在操作文件之前,通常需要检查文件是否存在:

string filePath = @"C:\example\test.txt";
if (File.Exists(filePath))
{Console.WriteLine("文件存在");
}
else
{Console.WriteLine("文件不存在");
}

1.2 创建、删除和移动文件

  • 创建文件

    File.Create(@"C:\example\newfile.txt");
  • 删除文件

    File.Delete(@"C:\example\oldfile.txt");
  • 移动/重命名文件

    File.Move(@"C:\example\oldname.txt", @"C:\example\newname.txt");
  • 复制文件

    File.Copy(@"C:\example\source.txt", @"C:\example\destination.txt");

2. 文本文件的读写

2.1 读取文本文件

C# 提供了多种读取文本文件的方式:

  • File.ReadAllText(读取整个文件)

    string content = File.ReadAllText(filePath);
    Console.WriteLine(content);
  • File.ReadAllLines(逐行读取)

    string[] lines = File.ReadAllLines(filePath);
    foreach (string line in lines)
    {Console.WriteLine(line);
    }
  • StreamReader(流式读取,适合大文件)

    using (StreamReader reader = new StreamReader(filePath))
    {string line;while ((line = reader.ReadLine()) != null){Console.WriteLine(line);}
    }

     

2.2 写入文本文件

  • File.WriteAllText(覆盖写入)

    File.WriteAllText(filePath, "Hello, World!");
  • File.AppendAllText(追加写入)

    File.AppendAllText(filePath, "\nThis is a new line.");
  • StreamWriter(流式写入)

    using (StreamWriter writer = new StreamWriter(filePath))
    {writer.WriteLine("Line 1");writer.WriteLine("Line 2");
    }

3. 二进制文件的读写

二进制文件(如图片、音频、数据库文件)需要使用 BinaryReader 和 BinaryWriter

3.1 写入二进制文件

using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
{writer.Write(100);         // 写入整数writer.Write(3.14);        // 写入双精度浮点数writer.Write("Hello");     // 写入字符串
}

3.2 读取二进制文件

using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{int number = reader.ReadInt32();double pi = reader.ReadDouble();string text = reader.ReadString();Console.WriteLine($"Number: {number}, Pi: {pi}, Text: {text}");
}

4. 文件流(FileStream)

FileStream 提供了更底层的文件访问方式,适用于大文件或需要精细控制的情况。

4.1 使用 FileStream 读写文件

// 写入文件
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{byte[] data = Encoding.UTF8.GetBytes("Hello, FileStream!");fs.Write(data, 0, data.Length);
}// 读取文件
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{byte[] buffer = new byte[1024];int bytesRead = fs.Read(buffer, 0, buffer.Length);string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);Console.WriteLine(content);
}

5. 目录操作

除了文件操作,C# 还提供了目录管理功能:

5.1 创建和删除目录

string dirPath = @"C:\example\newfolder";// 创建目录
Directory.CreateDirectory(dirPath);// 删除目录(recursive: true 表示删除非空目录)
Directory.Delete(dirPath, recursive: true);

5.2 遍历目录

// 获取所有文件
string[] files = Directory.GetFiles(dirPath);
foreach (string file in files)
{Console.WriteLine(file);
}// 获取所有子目录
string[] subDirs = Directory.GetDirectories(dirPath);
foreach (string dir in subDirs)
{Console.WriteLine(dir);
}

6. 异步文件操作

异步 I/O 可以提高程序性能,特别是在处理大文件时。

6.1 异步读取文件

async Task<string> ReadFileAsync(string path)
{using (StreamReader reader = new StreamReader(path)){return await reader.ReadToEndAsync();}
}

6.2 异步写入文件

async Task WriteFileAsync(string path, string content)
{using (StreamWriter writer = new StreamWriter(path)){await writer.WriteAsync(content);}
}

7. 文件操作的最佳实践

  1. 使用 using 语句:确保文件流正确关闭,避免资源泄漏。

  2. 异常处理:捕获 IOExceptionFileNotFoundException 等异常。

  3. 大文件处理:使用流式读取(StreamReader/FileStream)而非一次性读取全部内容。

  4. 路径处理:使用 Path.Combine 拼接路径,避免硬编码:

    string fullPath = Path.Combine(@"C:\example", "subfolder", "file.txt");
  5. 文件权限检查:在访问文件前检查权限(File.GetAccessControl)。

8. 总结

本文详细介绍了 C# 中的文件 I/O 操作,包括:

  • 基本文件操作(创建、删除、移动、复制)

  • 文本文件的读写(File.ReadAllTextStreamReader

  • 二进制文件的处理(BinaryReader/BinaryWriter

  • 文件流(FileStream)的使用

  • 目录管理(Directory 类)

  • 异步文件操作(ReadAsync/WriteAsync

  • 最佳实践(异常处理、资源释放、路径管理)

掌握这些技术后,你可以高效地处理各种文件操作需求,无论是小型配置文件还是大型数据文件。希望本文对你有所帮助!

 

http://www.lryc.cn/news/2394649.html

相关文章:

  • OpenCV 第7课 图像处理之平滑(二)
  • Visual Studio笔记:MSVC工具集、MSBuild
  • 【Netty系列】核心概念
  • Axure中继器交互完全指南:核心函数解析×场景实战×避坑策略(懂得才能应用)
  • DeepSeek 赋能数字人直播带货:技术革新重塑电商营销新生态
  • 高端制造行业 VMware 替代案例合集:10+ 头部新能源、汽车、半导体制造商以国产虚拟化支持 MES、PLM 等核心应用系统
  • 【b站计算机拓荒者】【2025】微信小程序开发教程 - chapter3 项目实践 - 3人脸识别采集统计人脸检测语音识别
  • 达梦的TEMP_SPACE_LIMIT参数
  • 24核32G,千兆共享:裸金属服务器的技术原理与优势
  • 杆塔倾斜在线监测装置:电力设施安全运行的“数字守卫”
  • C++23 新成员函数与字符串类型的改动
  • 在 ElementUI 中实现 Table 单元格合并
  • threejs渲染器和前端UI界面
  • AI笔记 - 网络模型 - mobileNet
  • day12 leetcode-hot100-20(矩阵3)
  • 【Java开发日记】基于 Spring Cloud 的微服务架构分析
  • 接口性能优化
  • AWTK 嵌入式Linux平台实现多点触控缩放旋转以及触点丢点问题解决
  • 尚硅谷redis7 93-97 springboot整合reids之总体概述
  • Flutter、React Native、Unity 下的 iOS 性能与调试实践:兼容性挑战与应对策略(含 KeyMob 工具经验)
  • 声纹技术体系:从理论基础到工程实践的完整技术架构
  • 行为型:命令模式
  • 构建多模型协同的Ollama智能对话系统
  • vue3 + WebSocket + Node 搭建前后端分离项目 开箱即用
  • Win10秘笈:两种方式修改网卡物理地址(MAC)
  • 【软件】navicat 官方免费版
  • 【深度学习】16. Deep Generative Models:生成对抗网络(GAN)
  • java操作服务器文件(把解析过的文件迁移到历史文件夹地下)
  • 特伦斯 S75 电钢琴:重构演奏美学的极致表达
  • STM32-标准库-GPIO-API函数