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

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


当前回答

File怎么样?ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

其他回答

用最少的c#代码最快的方法可能就是这个:

string readText = System.IO.File.ReadAllText(path);

File怎么样?ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

如果你想从应用程序的Bin文件夹中选择文件,那么你可以尝试以下操作,不要忘记做异常处理。

string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));

看一下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

你可以使用:

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