C#读写文本文件的多种方式详解

2025-07-06 18:50

本文主要是介绍C#读写文本文件的多种方式详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《C#读写文本文件的多种方式详解》这篇文章主要为大家详细介绍了C#中各种常用的文件读写方式,包括文本文件,二进制文件、CSV文件、JSON文件等,有需要的小伙伴可以参考一下...

C# 编程中,文件读写是一项非常基础且重要的操作。无论是保存用户数据、读取配置文件还是处理日志信息,都离不开文件操作。本文将详细介绍 C# 中各种常用的文件读写方式,包括文本文件、二进制文件、CSV 文件、JSON 文件等,并提供相应的代码示例,帮助你根据实际需求选择合适的方法。

一、文本文件读写

文本文件是最常见的文件类型,C# 提供了多种方式来读写文本文件。

1. 使用 File 类的静态方法

File 类提供了一系列静态方法,可以方便地进行文本文件的读写操作,适合处理小型文本文件。

using System;
using System.IO;
class Program
{
   static void Main()
   {
       // 写入文本文件
       string content = "Hello, World!";
       string path = "test.txt";

       // 写入所有文本
       File.WriteAllText(path, content);
       Console.WriteLine("文件写入成功");

       // 读取所有文本
       string readContent = File.ReadAllText(path);
       Console.WriteLine("读取的内容:" + readContent);


       // 写入多行文本
       string[] lines = { "第一行", "第二行", "第三行" };
       File.WriteAllLines(path, lines);
       Console.WriteLine("多行文本写入成功");

       // 读取所有行
       string[] readLines = File.ReadAllLines(path);
       Console.WriteLine("读取的多行内容:");
       foreach (string line in readLines)
       {
           Console.WriteLine(line);
       }
   }
}

优点:代码简洁,一行代码即可完成读写操作。

缺点:会将整个文件内容加载到内存中,不适合处理大型文件。

2. 使用 StreamReader 和 StreamWriter

StreamReader 和 StreamWriter 适合处理大型文本文件,可以逐行读写,节省内存。

using System;
using System.IO;

class Program
{
   static void Main()
   {
       string path = "largefile.txt";

       // 使用StreamWriter写入
       using (StreamWriter sw = new StreamWriter(path))
       {
           sw.WriteLine("第一行内容");
           sw.WriteLine("第二行内容");
           sw.Write("这是第三行的");
           sw.Write("一部分内容");
       }

       // 使用StreamReader读取
       using (StreamReader sr = new StreamReader(path))
       {
           string line;
           Console.WriteLine("文件内容:");
           while ((line = sr.ReadLine()) != null)
           {
               Console.WriteLine(line);
           }
       }

       // 读取全部内容
       using (StreamReader sr = new StreamReader(path))
       {
           string allContent = sr.ReadToEnd();
           Console.WriteLine("n全部内容:");
           Console.WriteLine(allContent);
       }
   }
}

优点:可以逐行处理,内存占用小,适合大型文件。

缺点:代码相对复杂一些。

注意:使用using语句可以确保流正确关闭和释放资源。

二、二进制文件读写

二进制文件适用于存储图像、音频、视频等非文本数据,或者需要紧凑存储的结构化数据。

1. 使用 FileStream 类

FileStream 是一个通用的字节流类,可以用于读写任何类型的文件。

using System;
using System.IO;

class Program
{
   static void Main()
   {
       string path = "data.bin";

       // 写入二进制数据
       byte[] data = { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64 }; // "Hello World"的ASCII码
       using (FileStream fs = new FileStream(path, FileMode.Create))
       {
           fs.Write(data, 0, data.Length);
       }

       // 读取二进制数据
       using (FileStream fs = new FileStream(path, FileMode.Open))
       {
           byte[] readData = new byte[fs.Length];
           fs.Read(readData, 0, readData.Length);

           CoChina编程nsole.WriteLine("读取的二进制数据转换为字符串:");
           Console.WriteLine(System.Text.Encoding.ASCII.GetString(readData));

           Console.WriteLine("十六进制表示:");

           foreach (byte b in readData)
           {
               Console.Write($"{b:X2} ");
           }
       }

   }
}

2. 使用 BinaryReader 和 BinaryWriter

BinaryReader 和 BinaryWriter 提供了更方便的方法来读写基本数据类型。

using System;
using System.IO;


class Program
{
   static void Main()
   {
       string path = "binarydata.bin";

       // 写入各种数据类型
       using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
       {
           bw.Write(123);           // int
           bw.Write(3.14159);       // double
           bw.Write(true);          // bool
           bw.Write("Hello World"); // string
           bw.Write(new char[] { 'a', 'b', 'c' }); // char数组
       }

       // 读取各种数据类型
       using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
       {
           Console.WriteLine("int值: " + br.ReadInt32());
           Console.WriteLine("double值: " + br.ReadDouble());
           Console.WriteLine("bool值: " + br.ReadBoolean());
           Console.WriteLine("string值: " + br.ReadString());

           char[] chars = br.ReadChars(3);
           Console.WriteLine("char数组: " + new string(chars));
       }
   }
}

注意:使用 BinaryReader 和 BinaryWriter 时,读取顺序必须与写入顺序一致。

三、使用 FileStream 进行高级操作

FileStream 提供了更多控制选项,适合需要精细控制文件操作的场景。

using System;
using System.IO;


class Program
{
   static void Main()
   {
       string sourcePath = "source.txt";
       string destPath = "destination.txt";


       // 创建源文件
       File.WriteAllText(sourcePath, "这是一个用于演示文件流操作的示例文本。");


       // 使用FileStream复制文件
       using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
       using (FileStream destStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
       {
           byte[] buffer = new byte[1024];
           int bytesRead;

           Console.WriteLine("开始复制文件...");

           // 每次读取1024字节并写入
           while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
           {
               destStream.Write(buffer, 0, bytesRead);
               Console.WriteLine($"已复制 {bytesRead} 字节");
           }

           Console.WriteLine("文件复制完成");
       }

       // 验证复制结果
       if (File.ReadAllText(sourcePath) == File.ReadAllText(destPath))
       {
           Console.WriteLine("复制的文件内容与源文件一致");
       }
   }
}

FileMode 枚举:控制打开或创建文件的方式,常见值有 Create、Open、Append 等。

FileAccess 枚举:指定对文件的访问权限,有 Read、Write、Readwrite。

缓冲操作:使用缓冲区可以提高大文件操作的效率。

四、特定格式文件读写

1. CSV 文件读写

CSV(逗号分隔值)文件是一种常见的表格数据格式。

using System;
using System.Collections.Generic;
using System.IO;


class Program
{
   static void Main()
   {
       string path = "data.csv";

       // 写入CSV文件
       var data = new List<string[]>
       {
           new[] { "姓名", "年龄", "城市" },
           new[] { "张三", "25", "北京" },
           new[] { "李四", "30", "上海" },
           new[] { "王五", "35", "广州" }
       };

       using (StreamWriter sw = new StreamWriter(path))
       {
           foreach (var row in data)
           {
               sw.WriteLine(string.Join(",", row));
           }
       }

       // 读http://www.chinasem.cn取CSV文件
       using (StreamReader sr = new StreamReader(path))
       {
           string line;
           while ((line = sr.ReadLine()) != null)
           {
               string[] columns = line.Split(',');
               Console.WriteLine(string.Join(" | ", columns));
           }
       }
   }
}

注意:以上是简单实现,实际应用中可能需要处理包含逗号的字段(通常用引号括起来),这时可以考虑使用专门的 CSV 库如 CsvHelper。

2. JSON 文件读写

JSON 是一种轻量级的数据交换格式,在现代应用中广泛使用。

需要先安装 Newtonsoft.Json 包(NuGet 命令:Install-Package Newtonsoft.Json)

using System;
using System.Collections.Generic;
using Newtonsoft.Json;


// 定义一个示例类
public class Person
{
   public string Name { get; set; }
   public int Age { get; set; }
   public string City { get; set; }
}


class Program
{
   static void Main()
   {
       string path = "people.json";

       // 创建示例数据
       var people = new List<Person>
       {
           new Person { Name = "张三", Age = 25, City = "北京" },
           new Person { Name = "李四", Age = 30, City = "上海" },
           new Person { Name = "王五", Age = 35, City = "广州" }
       };


       // 写入JSON文件
       string json = JsonConvert.SerializeObject(people, Formatting.Indented);
       File.WriteAllText(path, json);

       // 读取JSON文件
       string jsonFromFile = File.ReadAllText(path);
       List<Person> peopleFromFile = JsonConvert.DeserializeObject<List<Person>>(jsonFromFile);

       // 显示读取结果
       foreach (var person in peopleFromFile)
       {
           Console.WriteLine($"姓名: {person.Name}, 年龄: {person.Age}, 城市: {person.City}");
       }
   }
}

在.NET Core 3.0 及以上版本,也可以使用内置的 System.Text.Json:

// 写入JSON文件
string json = System.Text.Json.JsonSerializer.Serialize(people, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(path, json);


// 读取JSON文件
string jsonFromFile = File.ReadAllText(path);
List<Person> peopleFromFile = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(jsonFromFilPesOBKe);

五、文件操作的注意事项

1. 异常处理

文件操作可能会抛出各种异常,如文件不存在、权限不足等,需要进行适当的异常处理。

try
{
   string content = File.ReadAllText("test.txt");
   Console.WriteLine(content);
}
catch (FileNotFoundException)
{
   Console.WriteLine("文件不存在");
}
catch (UnauthorizedAccessException)
{
   Console.WriteLine("没有访问权限");
}
catch (IOException ex)
{
   Console.WriteLine($"IO错误: {ex.Message}");
}
catch (Exception ex)
{
   Console.WriteLine($"发生错误: {ex.Message}");
}

2. 路径处理

使用 Path 类来处理文件路径,避免跨平台问题。

// 组合路径
string directory = "data";
string fileName = "info.txt";
string fullPath = Path.Combine(directory, fileName);
Console.WriteLine("完整路径: " + fullPath);


// 获取文件名
Console.WriteLine("文件名: " + Path.GetFileName(fullPath));
python
// 获取文件扩展名
Console.WriteLine("扩展名: " + Path.GetExtension(fullPath));

// 获取目录名
Console.WriteLine("目录名: " + Path.GetDirectoryName(fullPath));

3. 异步操作

对于 UI 应用程序,使用异步文件操作可以避免界面卡顿。

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
   static async Task Main()
   {
       string path = "async_test.txt";

       // 异步写入
       string content = "这是一个异步写入的示例";
       await File.WriteAllTextAsync(path, content);
       Console.WriteLine("异步写入完成");

       // 异步读取
       string readContent = await File.ReadAllTextAsync(path);
       Console.WriteLine("异步读取内容: " + readContent);

       // 异步流操作
       using (StreamWriter sw = new StreamWriter(path, append: true))
       {
           await sw.WriteLineAsync("这是追加的一行");
       }


       using (StreamReader sr = new StreamReader(path))
       {
           string line;
           Console.WriteLine("文件内容:");
           while ((line = await sr.ReadLineAsync()) != null)
           {
               Console.WriteLine(line);
           }
       }
   }
}

六、总结

C# 提供了丰富的文件操作方式,选择合适的方法取决于具体需求:

  • 对于小型文本文件,File 类的静态方法最简单方便
  • 对于大型文本文件,StreamReader 和 StreamWriter 更合适
  • 对于二进制文件,使用 FileStream、BinaryReader 和 BinaryWriter
  • 对于 CSV 和 JSON 等特定格式,可使用相应的方法或库

无论使用哪种方式,都应该注意:

  • 使用 using 语句确保资源正确释放
  • 进行适当的异常处理
  • 注意路径处理和跨平台兼容性
  • 对于 UI 应用,优先考虑异步操作

掌握这些文件操作技巧,将有助于你更好地处理各种数据存储和读取需求,提高应用程序的灵活性和可靠性。

到此这篇关于C#读写文本文件的多种方式详解的文章就介绍到这了,更多相关C#读写文件内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(http://www.chinasem.cnwww.chinasem.cn)!

这篇关于C#读写文本文件的多种方式详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1155309

相关文章

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

从基础到进阶详解Python条件判断的实用指南

《从基础到进阶详解Python条件判断的实用指南》本文将通过15个实战案例,带你大家掌握条件判断的核心技巧,并从基础语法到高级应用一网打尽,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录​引言:条件判断为何如此重要一、基础语法:三行代码构建决策系统二、多条件分支:elif的魔法三、

Java利用@SneakyThrows注解提升异常处理效率详解

《Java利用@SneakyThrows注解提升异常处理效率详解》这篇文章将深度剖析@SneakyThrows的原理,用法,适用场景以及隐藏的陷阱,看看它如何让Java异常处理效率飙升50%,感兴趣的... 目录前言一、检查型异常的“诅咒”:为什么Java开发者讨厌它1.1 检查型异常的痛点1.2 为什么说

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

Linux系统管理与进程任务管理方式

《Linux系统管理与进程任务管理方式》本文系统讲解Linux管理核心技能,涵盖引导流程、服务控制(Systemd与GRUB2)、进程管理(前台/后台运行、工具使用)、计划任务(at/cron)及常用... 目录引言一、linux系统引导过程与服务控制1.1 系统引导的五个关键阶段1.2 GRUB2的进化优

springboot2.1.3 hystrix集成及hystrix-dashboard监控详解

《springboot2.1.3hystrix集成及hystrix-dashboard监控详解》Hystrix是Netflix开源的微服务容错工具,通过线程池隔离和熔断机制防止服务崩溃,支持降级、监... 目录Hystrix是Netflix开源技术www.chinasem.cn栈中的又一员猛将Hystrix熔

Java调用Python脚本实现HelloWorld的示例详解

《Java调用Python脚本实现HelloWorld的示例详解》作为程序员,我们经常会遇到需要在Java项目中调用Python脚本的场景,下面我们来看看如何从基础到进阶,一步步实现Java与Pyth... 目录一、环境准备二、基础调用:使用 Runtime.exec()2.1 实现步骤2.2 代码解析三、

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图