Valhalla Legends Archive

Programming => General Programming => .NET Platform => Topic started by: Dale on June 27, 2007, 01:05 PM

Title: C#.Net Reading Text Files
Post by: Dale on June 27, 2007, 01:05 PM
How would I go about, reading every some lines, in a text file?

I know how to read from a file, and that works, I just can't seem to get it to read say, every 7 lines.

Any help would be appreciated!
Title: Re: C#.Net Reading Text Files
Post by: shout on June 27, 2007, 01:54 PM

public static string[] ReadLines(string file, int skip)
{
string[] s = new string[0];
StreamReader sr = new StreamReader(file);
for (int i = 0; ;i++)
{
try
{
string st = sr.ReadLine();
if (i % skip == 0)
{
string[] sn = new string[s.Length + 1];
Array.Copy(s, 0, sn, 0, s.Length);
sn[sn.Length - 1] = st;
s = sn;
}
}
catch (System.IO.IOException e)
{
sr.Close();
}
}
return s;
}


I didn't test this but it should look something like this.
Title: Re: C#.Net Reading Text Files
Post by: Dale on June 27, 2007, 02:08 PM
Thanks, But since that shit totally confuses me, I get an "Unreachable Code Detected" and return s; is underlined, how do I fix this?
Title: Re: C#.Net Reading Text Files
Post by: shout on June 27, 2007, 03:58 PM
Err...

put

break;

after sr.Close();

And what don't you understand about it? I'll do my best to explain.
Title: Re: C#.Net Reading Text Files
Post by: iNsaNe on September 28, 2007, 10:32 PM
use System.IO.File, you will probably want System.IO.File.ReadAllText or ReadAllLines. There is also a function to ReadAllBytes.
Title: Re: C#.Net Reading Text Files
Post by: MyndFyre on September 30, 2007, 01:26 AM
Quote from: iNsaNe on September 28, 2007, 10:32 PM
use System.IO.File, you will probably want System.IO.File.ReadAllText or ReadAllLines. There is also a function to ReadAllBytes.
Couple thoughts....

First, this thread had been dead for a while....

The second, is that using StreamReader.ReadLine() is probably more effective to code in this case, because the StreamReader object handles parsing each line.  On the other hand, if you use File.ReadAllText(), you need to split the string out.  I suspect that ReadLine() makes it a bit clearer in intent as well.
Title: Re: C#.Net Reading Text Files
Post by: Dale on September 30, 2007, 11:31 AM
I could of just read the whole file, and put it into an array..