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

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


当前回答

你可以使用:

 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);
    }
}

其他回答

你可以这样用

public static string ReadFileAndFetchStringInSingleLine(string file)
    {
        StringBuilder sb;
        try
        {
            sb = new StringBuilder();
            using (FileStream fs = File.Open(file, FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamReader sr = new StreamReader(bs))
                    {
                        string str;
                        while ((str = sr.ReadLine()) != null)
                        {
                            sb.Append(str);
                        }
                    }
                }
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            return "";
        }
    }

希望这对你有所帮助。

看一下File.ReadAllText()方法

一些重要备注:

This method opens a file, reads each line of the file, and then adds each line as an element of a string. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed. This method attempts to automatically detect the encoding of a file based on the presence of byte order marks. Encoding formats UTF-8 and UTF-32 (both big-endian and little-endian) can be detected. Use the ReadAllText(String, Encoding) method overload when reading files that might contain imported text, because unrecognized characters may not be read correctly. The file handle is guaranteed to be closed by this method, even if exceptions are raised

string content = System.IO.File.ReadAllText( @"C:\file.txt" );

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

文件操作读取结果:

对于小文件(只有8行)

对于较大的文件(128465行)

readline的例子:

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

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

对于那些觉得这个东西有趣和有趣的新手来说,在大多数情况下(根据这些基准测试)将整个文件读入字符串的最快方法是通过以下方法:

using (StreamReader sr = File.OpenText(fileName))
{
        string s = sr.ReadToEnd();
}
//you then have to process the string

然而,绝对最快的读取文本文件的整体似乎是以下:

using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
               //do what you have to here
        }
}

与其他几种技术相比,它在大多数情况下胜出,包括与BufferedReader的竞争。