Reading a string line per line in C# [duplicate]
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
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);
Check for null when you do a readLine - see the docs.
The StreamReader class has an EndOfStream property. Have you looked into using that?
Like this:
string line;
while (null != (line = reader.ReadLine()) {
Process(line);
}
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
}
Dismissile is correct:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.endofstream.aspx
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
精彩评论