将文本文件读入字符串变量的最快方法是什么?

我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。


当前回答

System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();

其他回答

你也可以从文本文件中读取文本到字符串,如下所示

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

我强烈建议使用File. readlines(路径)相比StreamReader或任何其他文件读取方法。请在下面找到小文件和大文件的详细性能基准。 我希望这能有所帮助。

文件操作读取结果:

对于小文件(只有8行)

对于较大的文件(128465行)

readline的例子:

public void ReadFileUsingReadLines()
{
    var contents = File.ReadLines(path);
}

注意:基准测试是在。net 6中完成的。

你可以使用:

 public static void ReadFileToEnd()
{
    try
    {
    //provide to reader your complete text file
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line = sr.ReadToEnd();
            Console.WriteLine(line);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}

File怎么样?ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();