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

相关文章

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

MyBatis常用XML语法详解

《MyBatis常用XML语法详解》文章介绍了MyBatis常用XML语法,包括结果映射、查询语句、插入语句、更新语句、删除语句、动态SQL标签以及ehcache.xml文件的使用,感兴趣的朋友跟随小... 目录1、定义结果映射2、查询语句3、插入语句4、更新语句5、删除语句6、动态 SQL 标签7、ehc

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

从基础到高级详解Go语言中错误处理的实践指南

《从基础到高级详解Go语言中错误处理的实践指南》Go语言采用了一种独特而明确的错误处理哲学,与其他主流编程语言形成鲜明对比,本文将为大家详细介绍Go语言中错误处理详细方法,希望对大家有所帮助... 目录1 Go 错误处理哲学与核心机制1.1 错误接口设计1.2 错误与异常的区别2 错误创建与检查2.1 基础

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文解析C#中的StringSplitOptions枚举

《一文解析C#中的StringSplitOptions枚举》StringSplitOptions是C#中的一个枚举类型,用于控制string.Split()方法分割字符串时的行为,核心作用是处理分割后... 目录C#的StringSplitOptions枚举1.StringSplitOptions枚举的常用

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D