19

Possible Duplicate:
Easiest way to split a string on newlines in .net?

I'm trying to read out and interpret a string line per line. I took a look at the StringReader class, but I need to find out when I'm on the last line. Here's some pseudocode of what I'm trying to accomplish:

while (!stringReaderObject.atEndOfStream()) {
    interpret(stringReaderObject.readLine());
}

Does somebody know how to do this?

Thanks!

Yvan

Community
  • 1
  • 1
friedkiwi
  • 2,158
  • 8
  • 29
  • 52
  • 2
    Not really a duplicate... both questions have different solutions. – AStopher Dec 13 '16 at 16:07
  • Here's the solution that worked for me: `private static IEnumerable ReadAllLines(string multiLineString) { if (string.IsNullOrEmpty(multiLineString)) yield break; // Nothing to do using (var reader = new StringReader(multiLineString)) { string line; while ((line = reader.ReadLine()) is object) { yield return line; } } }` – Mark Moore Mar 10 '21 at 21:16

6 Answers6

76

If you are reading it in from a file, it is easier to do just do:

foreach(var myString in File.ReadAllLines(pathToFile))
    interpret(myString);

If you are getting the string from somewhere else (a web service class or the like) it is simpler to just split the string:

foreach(var myString in entireString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
    interpret(myString);
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • what if his string has \r\n new lines and he's on Unix? – NG. Oct 21 '10 at 17:05
  • 1
    @SB then I'm sure he would have added the "mono" and "interop" tags ;-) – Klaus Byskov Pedersen Oct 21 '10 at 17:08
  • 4
    Worth mentioning is `File.ReadLines` (.Net 4.0) which returns a `IEnumerable` so you get lines while reading the file which is better in two ways: 1. You don't have the whole line-array in memory if you don't need it. 2. `ReadAllLines` reads the whole file before you get a single line where `ReadLines` will give you the first line as soon as it is read. (more responsive). Because he is calling a method on each line which interprets it, he properly wants `ReadLines` and not `ReadAllLines`. – Lasse Espeholt Oct 21 '10 at 17:44
  • **Doesn't work for me**. The best overloaded method match for 'string.Split(params char[])' has some invalid arguments – Colonel Panic Oct 02 '12 at 09:47
  • @ColonelPanic, sorry the example was flawed. I have updated it. Hope it helps. – Klaus Byskov Pedersen Oct 02 '12 at 09:53
  • Thanks Klaus. Also, imho StringSplitOptions.None is a better choice, because RemoveEmptyEntries could break Markdown, eg. `"Header\r\n=====\r\n\r\nParagraph".Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)` – Colonel Panic Oct 02 '12 at 10:00
  • @ColonelPanic, Well I guess that depends what you use it for. But if you are parsing Markdown I suppose you are right. – Klaus Byskov Pedersen Oct 02 '12 at 10:02
  • Thanks @KlausByskovPedersen You saved my much time. I have used your solution to read the each line of string getting from somewhere else (string got from WebClient DownloadString from online Text file). – ThermeshB Jun 08 '23 at 12:25
4

Like this:

string line;
while (null != (line = reader.ReadLine()) {
    Process(line);
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    No. Like this: `while(true) { string line = reader.ReadLine(); if(line == null) { break; } Process(line); }`. That single line of code is doing too much. – jason Oct 21 '10 at 17:04
  • 2
    @Jason - not really. Also it's the canonical pattern of use in every example I've ever seen. – Kev Oct 21 '10 at 17:10
  • @Kev: It's like a bad habit passed from generation to generation. – jason Oct 21 '10 at 17:34
  • 2
    @Jason - no it's not. It's succinct and entirely readable. You're taking single responsibility way too far. – Kev Oct 21 '10 at 18:25
  • 1
    @Kev: Since this has nothing to do with SRP, I'm not. This is mostly about readability, and to a certain extent maintainability. Succinct code is not necessarily readable code. – jason Oct 21 '10 at 18:29
  • 1
    @Jason - there's nothing hard to read about that code. Hell, I'm an ex-VB/Clipper programmer and could understand that when I started out with .NET. That extra `if()` is just a distraction. – Kev Oct 21 '10 at 19:08
  • @Kev: I didn't say it is hard to read. – jason Oct 21 '10 at 20:41
4

Check for null when you do a readLine - see the docs.

NG.
  • 22,560
  • 5
  • 55
  • 61
2

The StreamReader class has an EndOfStream property. Have you looked into using that?

Dismissile
  • 32,564
  • 38
  • 174
  • 263
2

I am not sure where you are reading from. If it is from the Console, you can check for the end of inputs string like "quit" to denote end of input

String input;
while((input = reader.readLine()) != "quit"){
   // do something
}
user
  • 377
  • 4
  • 13
1

Dismissile is correct:

http://msdn.microsoft.com/en-us/library/system.io.streamreader.endofstream.aspx

while (!reader.EndOfStream) 
{ 
    string line = reader.ReadLine(); 
} 
Kirit Chandran
  • 679
  • 7
  • 13