File.ReadAllLines or Stream Reader(File.ReadAllLines 或 Stream Reader)
问题描述
我们可以使用 StreamReader
或使用 File.ReadAllLines
.
We can read file either by using StreamReader
or by using File.ReadAllLines
.
例如,我想将每一行加载到 List
或 string[]
中,以便对每一行进行进一步操作.
For example I want to load each line into a List
or string[]
for further manipulation on each line.
string[] lines = File.ReadAllLines(@"C:\file.txt");
foreach(string line in lines)
{
//DoSomething(line);
}
或
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
应用程序遇到不同大小的文本文件.偶尔会从几个 KBs
增长到 MBs
.
Application come across different size of text file. Which could grow from few KBs
to MBs
occasionally.
我的问题是哪一种是首选方式,为什么应该优先选择其他方式?
My question is that which one is preferred way and why one should be preferred over other?
推荐答案
如果你想处理一个文本文件的每一行而不将整个文件加载到内存中,最好的方法是这样的:
If you want to process each line of a text file without loading the entire file into memory, the best approach is like this:
foreach (var line in File.ReadLines("Filename"))
{
// ...process line.
}
这避免了加载整个文件,并使用现有的 .Net 函数来完成.
This avoids loading the entire file, and uses an existing .Net function to do so.
但是,如果由于某种原因需要将所有字符串存储在一个数组中,最好只使用 File.ReadAllLines()
- 但如果您只使用 foreach
访问数组中的数据,然后使用File.ReadLines()
.
However, if for some reason you need to store all the strings in an array, you're best off just using File.ReadAllLines()
- but if you are only using foreach
to access the data in the array, then use File.ReadLines()
.
这篇关于File.ReadAllLines 或 Stream Reader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:File.ReadAllLines 或 Stream Reader


- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01