开发者

Parse text file with LINQ

开发者 https://www.devze.com 2023-02-07 09:32 出处:网络
I know normally you would use the 开发者_开发百科File.ReadAllLines, but I\'m trying to do it with an uploaded file.

I know normally you would use the 开发者_开发百科File.ReadAllLines, but I'm trying to do it with an uploaded file.

Can I somehow put it into a temporary location?, or read it from memory?

I was able to get this working


Is this a string, a Stream, or what? either way, you want a TextReader - the question is simply StringReader vs StreamReader. Once you have that, I would do something like:

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

then with whichever reader, I can either user:

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

or:

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

i.e. if it is a Stream you are reading from:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号