跳到主要内容

C# 文本文件处理

在C#编程中,处理文本文件是一项常见的任务。无论是读取配置文件、记录日志,还是处理用户输入,文本文件都是存储和传输数据的常用方式。本文将介绍如何在C#中处理文本文件,包括读取、写入和操作文本文件的基本操作。

1. 读取文本文件

在C#中,读取文本文件的最简单方法是使用 System.IO.File 类的 ReadAllText 方法。该方法将整个文件内容读取为一个字符串。

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = "example.txt";
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
}
}

输入文件 example.txt 内容:

Hello, World!
This is a sample text file.

输出:

Hello, World!
This is a sample text file.
备注

ReadAllText 方法适用于较小的文件。对于较大的文件,建议使用流式读取方法,如 StreamReader

2. 写入文本文件

要将文本写入文件,可以使用 File.WriteAllText 方法。该方法将指定的字符串写入文件,如果文件已存在,则覆盖其内容。

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = "output.txt";
string content = "This is a new text file.";
File.WriteAllText(filePath, content);
Console.WriteLine("File written successfully.");
}
}

输出文件 output.txt 内容:

This is a new text file.
提示

如果你想追加内容而不是覆盖文件,可以使用 File.AppendAllText 方法。

3. 逐行读取文本文件

对于较大的文件,逐行读取是更高效的方式。可以使用 StreamReader 类来实现这一点。

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}

输入文件 example.txt 内容:

Line 1
Line 2
Line 3

输出:

Line 1
Line 2
Line 3

4. 逐行写入文本文件

类似地,可以使用 StreamWriter 类逐行写入文本文件。

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = "output.txt";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
writer.WriteLine("Line 3");
}
Console.WriteLine("File written successfully.");
}
}

输出文件 output.txt 内容:

Line 1
Line 2
Line 3

5. 实际应用场景

5.1 日志记录

日志记录是文本文件处理的常见应用场景。以下是一个简单的日志记录示例:

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string logFilePath = "log.txt";
Log("Application started.", logFilePath);
Log("Performing some operations...", logFilePath);
Log("Application ended.", logFilePath);
}

static void Log(string message, string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine($"{DateTime.Now}: {message}");
}
}
}

输出文件 log.txt 内容:

2023-10-01 12:00:00: Application started.
2023-10-01 12:00:01: Performing some operations...
2023-10-01 12:00:02: Application ended.

5.2 配置文件读取

配置文件通常以文本文件的形式存储。以下是一个读取配置文件的示例:

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string configFilePath = "config.txt";
string[] configLines = File.ReadAllLines(configFilePath);

foreach (string line in configLines)
{
string[] keyValue = line.Split('=');
if (keyValue.Length == 2)
{
Console.WriteLine($"Key: {keyValue[0]}, Value: {keyValue[1]}");
}
}
}
}

输入文件 config.txt 内容:

username=admin
password=secret

输出:

Key: username, Value: admin
Key: password, Value: secret

6. 总结

本文介绍了如何在C#中处理文本文件,包括读取、写入和操作文本文件的基本操作。我们通过实际应用场景展示了这些操作的实际用途。希望这些内容能帮助你更好地理解和应用C#中的文本文件处理。

7. 附加资源与练习

  • 练习1:编写一个程序,读取一个文本文件并统计其中的行数、单词数和字符数。
  • 练习2:创建一个日志记录器类,允许用户指定日志文件的路径,并提供方法记录不同级别的日志(如信息、警告、错误)。
警告

在处理文件时,请始终注意异常处理,以防止文件不存在或无法访问等问题。