File.ReadAllLines或流读取

编程入门 行业动态 更新时间:2024-10-09 10:29:57
本文介绍了File.ReadAllLines或流读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们可以通过使用 的StreamReader 或使用 File.ReadAllLines 。

We can read file either by using StreamReader or by using File.ReadAllLines.

例如我想行的每一行加载到列表或字符串[ ] 为每行进一步的操作。

For example I want to load each line of 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

应用遇到不同大小的文本文件。这可以从几个 KB为到 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或流读取

本文发布于:2023-11-03 23:54:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:File   ReadAllLines

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!