将文本文件读入字符串变量的最快方法是什么?
我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。
将文本文件读入字符串变量的最快方法是什么?
我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。
当前回答
对于那些觉得这个东西有趣和有趣的新手来说,在大多数情况下(根据这些基准测试)将整个文件读入字符串的最快方法是通过以下方法:
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的竞争。
其他回答
string contents = System.IO.File.ReadAllText(path)
这是MSDN文档
@Cris抱歉,这是微软的MSDN
方法
在这个实验中,将对两个班级进行比较。StreamReader和FileStream类将被指示从应用程序目录中读取两个10K和200K的完整文件。
StreamReader (VB.NET)
sr = New StreamReader(strFileName)
Do
line = sr.ReadLine()
Loop Until line Is Nothing
sr.Close()
FileStream (VB.NET)
Dim fs As FileStream
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Dim b(1024) As Byte
fs = File.OpenRead(strFileName)
Do While fs.Read(b, 0, b.Length) > 0
temp.GetString(b, 0, b.Length)
Loop
fs.Close()
结果
在这个测试中,FileStream明显更快。StreamReader读取小文件需要额外50%的时间。对于大文件,它需要额外的27%的时间。
StreamReader是专门寻找换行符,而FileStream没有。这将占用一些额外的时间。
建议
根据应用程序需要对某段数据做什么,可能会有额外的解析,这将需要额外的处理时间。考虑这样一个场景,其中文件有数据列,行是CR/LF分隔的。StreamReader将沿着文本行查找CR/LF,然后应用程序将执行额外的解析以查找数据的特定位置。(你认为弦。子字符串没有价格?)
另一方面,FileStream以块的形式读取数据,积极主动的开发人员可以编写更多的逻辑来使用流。如果需要的数据位于文件中的特定位置,这当然是一种方法,因为它可以降低内存使用量。
FileStream在速度上是更好的机制,但需要更多的逻辑。
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
你可以使用:
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 "";
}
}
希望这对你有所帮助。