Has*_*san 6 .net c# stream winforms
我们可以通过使用StreamReader或使用来读取文件File.ReadAllLines.
例如,我想将每一行加载到每一行List或string[]进行进一步操作.
string[] lines = File.ReadAllLines(@"C:\\file.txt");
foreach(string line in lines)
{
//DoSomething(line);
}
Run Code Online (Sandbox Code Playgroud)
要么
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//DoSomething(line); or //save line into List<string>
}
}
//if list is created loop through list here
Run Code Online (Sandbox Code Playgroud)
应用程序遇到不同大小的文本文件.哪个可以从少数增长KBs到MBs偶尔.
我的问题是,哪一个是首选方式,为什么一个应该优先于其他方式?
Mat*_*son 15
如果要处理文本文件的每一行而不将整个文件加载到内存中,最好的方法是这样的:
foreach (var line in File.ReadLines("Filename"))
{
// ...process line.
}
Run Code Online (Sandbox Code Playgroud)
这样可以避免加载整个文件,并使用现有的.Net函数来执行此操作.
但是,如果由于某种原因需要将所有字符串存储在数组中,那么最好只使用File.ReadAllLines()- 但如果您只是foreach用来访问数组中的数据,那么请使用File.ReadLines().
Sam*_*Axe 13
Microsoft在File.ReadAllLines中使用StreamReader:
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
逐行读取StreamReader文件,会消耗更少的内存。而一次File.ReadAllLines读取所有行并将其存储到 中,则会消耗更多内存。如果大于的话就会产生内存溢出(32位操作系统的限制)。string[]string[]int.maxvalue
所以,对于更大的文件StreamReader会更有效率。