C# File.ReadAllText()方法: 读取指定文件的所有文本

  • Post category:C#

C#中的File.ReadAllText()方法用于读取文本文件中的所有内容并将其存储为一个字符串,其语法格式如下:

public static string ReadAllText (string path);

该方法接受一个字符串类型的参数,该参数表示要读取的文本文件的路径和文件名。

该方法在读取文件时会将文件的所有内容放到一个字符串中,所以该方法适用于当需要一次性读取整个文本文件的内容,并且该文件不是非常大的情况下。

下面是两个关于File.ReadAllText()的使用实例:

实例一

假设我们有一个包含学生姓名和成绩的文本文件“score.txt”,该文件的内容如下:

John,87
Cindy,93
Peter,75

我们想要读取该文件中的所有内容并处理文件数据,可以使用以下代码:

string filePath = @"D:\score.txt";
string fileContent = File.ReadAllText(filePath);
string[] lines = fileContent.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

foreach(string line in lines)
{
    string[] arrs = line.Split(new char[] {','});
    string name = arrs[0].Trim();
    int score = int.Parse(arrs[1].Trim());

    // 在这里进行进一步处理
}

在这段代码中,首先使用File.ReadAllText()方法读取文件“score.txt”的所有内容,并将结果保存到一个字符串变量fileContent中。接着,使用字符串的Split()方法按行将整个文件切割为一个个字符串数组元素。对于每个字符串数组的元素,使用Split()方法按照逗号将它们切割为两部分,即名字和分数。最后,将名字和分数按照需要进行进一步的处理。

实例二

假设我们需要将一个系统工具的日志文件(log.txt)解析为易读的格式,并将解析后的文本写到一个新的文件(log_new.txt)中。该日志文件的内容如下:

[2022-01-01 23:59:59] start the system tool and login with username john
[2022-01-01 23:59:59] operation1 takes 10.23 seconds and returns result: 56
[2022-01-01 23:59:59] operation2 takes 5.86 seconds and throws an exception: System.NullReferenceException
[2022-01-01 23:59:59] operation3 takes 15.47 seconds and returns result: 1024

可以使用以下代码将该日志文件解析为易读的格式并存储到新的文件中:

string filePath = @"D:\log.txt";
string newFilePath = @"D:\log_new.txt";
string fileContent = File.ReadAllText(filePath);
StringBuilder sb = new StringBuilder();

string[] lines = fileContent.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

foreach(string line in lines)
{
    // 匹配日志行的正则表达式
    string pattern = @"^\[(?<date>.+)\]\s(?<content>.+)$";
    Match match = Regex.Match(line, pattern);

    if(match.Success)
    {
        DateTime date = DateTime.Parse(match.Groups["date"].Value);
        string content = match.Groups["content"].Value;

        // 判断消息类型
        if(content.Contains("start the system tool"))
        {
            sb.AppendLine($"[{date.ToString("HH:mm:ss")}] System tool starts");
        }
        else if(content.Contains("operation"))
        {
            int startPos = content.IndexOf("takes") + 5;
            int endPos = content.IndexOf("seconds");
            double seconds = double.Parse(content.Substring(startPos, endPos - startPos).Trim());

            if(content.Contains("returns result:"))
            {
                int result = int.Parse(content.Substring(content.IndexOf("returns result:") + 15).Trim());
                sb.AppendLine($"[{date.ToString("HH:mm:ss")}] Operation returns {result} after {seconds:F2} seconds");
            }
            else if(content.Contains("throws an exception:"))
            {
                string exception = content.Substring(content.IndexOf("throws an exception:") + 20).Trim();
                sb.AppendLine($"[{date.ToString("HH:mm:ss")}] Operation throws exception \"{exception}\" after {seconds:F2} seconds");
            }
        }
    }
}

// 将解析后的日志写入新文件
File.WriteAllText(newFilePath, sb.ToString(), Encoding.UTF8);

在这段代码中,首先使用File.ReadAllText()方法读取文件“log.txt”的所有内容,并将结果保存到一个字符串变量fileContent中。接着,使用字符串的Split()方法按行将整个文件切割为一个个字符串数组元素。对于每个字符串数组的元素,使用正则表达式匹配具有时间戳和详细内容的消息。使用DateTime.Parse()方法将日志中的时间戳解析为一个DateTime类型的对象。根据消息的内容判断消息类型,并使用StringBuilder动态构造第二个文件中的内容。最后,使用File.WriteAllText()方法将StringBuilder对象中的内容写入到一个新文件“log_new.txt”中。