mar*_*c_s 350
怎么样
string contents = File.ReadAllText(@"C:\temp\test.txt");
Run Code Online (Sandbox Code Playgroud)
Dev*_*van 162
来自C#文件处理的File.ReadAllLines
vs 的基准比较StreamReader ReadLine
结果.对于具有10,000多行的大型文件,StreamReader要快得多,但较小文件的差异可以忽略不计.与往常一样,计划不同大小的文件,并仅在性能不重要时使用File.ReadAllLines.
由于File.ReadAllText
其他人已经提出了这种方法,您也可以更快地尝试(我没有定量测试性能影响,但它似乎比File.ReadAllText
(见下面的比较)更快). 只有在文件较大的情况下,才能看到性能上的差异.
string readContents;
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
readContents = streamReader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
通过ILSpy查看指示性代码我发现了以下关于File.ReadAllLines
,File.ReadAllText
.
File.ReadAllText
- StreamReader.ReadToEnd
内部使用File.ReadAllLines
- 还在StreamReader.ReadLine
内部使用额外的开销,创建List<string>
返回作为读取行并循环直到文件结束.
因此,这两种方法都是建立在其上的额外的便利层StreamReader
.这通过该方法的指示性主体是显而易见的.
File.ReadAllText()
由ILSpy反编译的实现
public static string ReadAllText(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
}
return File.InternalReadAllText(path, Encoding.UTF8);
}
private static string InternalReadAllText(string path, Encoding encoding)
{
string result;
using (StreamReader streamReader = new StreamReader(path, encoding))
{
result = streamReader.ReadToEnd();
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
Nei*_*ell 16
string contents = System.IO.File.ReadAllText(path)
Run Code Online (Sandbox Code Playgroud)
这是MSDN文档
小智 7
对于那些发现这些东西有趣而有趣的菜鸟来说,在大多数情况下(根据这些基准)将整个文件读入字符串的最快方法如下:
using (StreamReader sr = File.OpenText(fileName))
{
string s = sr.ReadToEnd();
}
//you then have to process the string
Run Code Online (Sandbox Code Playgroud)
但是,读取文本文件的绝对最快速度似乎如下:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do what you have to here
}
}
Run Code Online (Sandbox Code Playgroud)
与其他几种技术对抗,它在大多数情况下都胜出,包括对抗 BufferedReader。
看一下File.ReadAllText()方法
一些重要的评论:
此方法打开一个文件,读取文件的每一行,然后将每一行添加为字符串的元素.然后它关闭文件.一行被定义为一个字符序列,后跟一个回车符('\ r'),一个换行符('\n')或一个回车符后面紧跟一个换行符.生成的字符串不包含终止回车符和/或换行符.
此方法尝试根据字节顺序标记的存在自动检测文件的编码.可以检测到编码格式UTF-8和UTF-32(big-endian和little-endian).
读取可能包含导入文本的文件时,请使用ReadAllText(String,Encoding)方法重载,因为可能无法正确读取无法识别的字符.
即使引发了异常,也可以保证此方法关闭文件句柄
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
string text = File.ReadAllText("Path");
你有一个字符串变量中的所有文本.如果您需要单独使用每一行,您可以使用:
string[] lines = File.ReadAllLines("Path");
Run Code Online (Sandbox Code Playgroud)
如果您想从应用程序的 Bin 文件夹中选择文件,那么您可以尝试以下操作,并且不要忘记进行异常处理。
string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));
Run Code Online (Sandbox Code Playgroud)