HOWTO · Csharp

在 C# 中读取文件到字符串

可使用两种主要方法将文件的所有内容读取到 C# 中的字符串变量中,即 File.ReadAllText()函数和 StreamReader.ReadToEnd()函数。

本页内容

本教程将讨论在 C# 中将文件的所有内容读取为字符串变量的方法。

在 C# 中使用 File.ReadAllText() 方法将文件读取为字符串

File 类提供了许多与 C# 中的文件进行交互的功能。C# 中的 File.ReadAllText() 方法(File.ReadAllText 方法(System.IO)| Microsoft Docs)读取文件的所有内容。File.ReadAllText() 方法将文件的路径作为参数,并以字符串变量返回指定文件的内容。请参见以下示例代码。

using System;
using System.IO;

namespace read_file_to_string {
  class Program {
    static void Main(string[] args) {
      string text = File.ReadAllText(@"C:\File\file.txt");
      Console.WriteLine(text);
    }
  }
}

输出:

this is all the text in this file

在上面的代码中,我们使用 C# 中的 File.ReadAllText() 方法将路径 C:\File\内文件 file.txt 的所有内容读取到字符串变量 text 中。

在 C# 中使用 StreamReader.ReadToEnd() 方法将文件读取为字符串

StreamReader 类从字节流中读取具有 C# 特定编码的内容。StreamReader.ReadToEnd() 方法用于读取 C# 中文件的所有内容。StreamReader.ReadToEnd() 方法以字符串变量返回指定文件的内容。请参见以下示例代码。

using System;
using System.IO;

namespace read_file_to_string {
  class Program {
    static void Main(string[] args) {
      StreamReader fileReader = new StreamReader(@"C:\File\file.txt");
      string text = fileReader.ReadToEnd();
      Console.WriteLine(text);
    }
  }
}

输出:

this is all the text in this file

在上面的代码中,我们使用 C# 中的 StreamReader.ReadToEnd() 方法将路径 C:\File\内文件 file.txt 的所有内容读取到字符串变量 text 中。这种方法比以前的方法快得多。