c# - 使用 LINQ 解析文本文件

标签 c# linq text-parsing

我知道通常您会使用 File.ReadAllLines,但我正在尝试使用上传的文件来执行此操作。

我能否以某种方式将其放入临时位置?或者从内存中读取?

我能够让它工作

最佳答案

这是 stringStream 还是什么?无论哪种方式,您都需要一个 TextReader - 问题很简单,就是 StringReader vs StreamReader。一旦你有了那个,我会做类似的事情:

public static IEnumerable<string> ReadLines(TextReader reader) {
    string line;
    while((line = reader.ReadLine()) != null) yield return line;
}

然后无论使用哪个阅读器,我都可以使用:

foreach(var line in ReadLines(reader)) {
    // note: non-buffered - i.e. more memory-efficient
}

或:

string[] lines = ReadLines(reader).ToArray();
// note: buffered - all read into memory at once (less memory efficient)

即如果它是一个 Stream 你正在阅读:

using(var reader = new StreamReader(inputStream)) {
    foreach(var line in ReadLines(reader)) {
        // do something fun and interesting
    }
}

关于c# - 使用 LINQ 解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4825589/

相关文章:

C#根据特定的结构成员值从数组中获取结构

perl - 在 Perl 中,如何正确解析带引号的字符串的制表符/空格分隔文件?

c# - VB.NET 中的 volatile 等价物

c# - 如何创建用于在 C# 中描述对象的自定义语法?

c# - 如何让另存为对话框出现 "early"?或者 : How to make Flush() behave correctly?

java - 从包含转义字符的文件中读取文本以进行等效的编译时间

parsing - 帮助解析日志文件 (ANTLR3)

c# - C# 中的 Currying 有什么优势? (实现部分功能)

c# - 在局部 View mvc 中显示三篇随机文章

c# - 在 .Any() LINQ 查询中将 'string' 转换为 'int'