Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lines of a StreamReader to an array of string

I want to get a string[] assigned with a StreamReader. Like:

try{
    StreamReader sr = new StreamReader("a.txt");
    do{
        str[i] = sr.ReadLine();
        i++;
    }while(i < 78);
}
catch (Exception ex){
    MessageBox.Show(ex.ToString());
}

I can do it but can't use the string[]. I want to do this:

MessageBox.Show(str[4]);

If you need further information feel free to ask, I will update. thanks in advance...

like image 392
whoone Avatar asked Dec 09 '22 20:12

whoone


1 Answers

If you really want a string array, I would approach this slightly differently. Assuming you have no idea how many lines are going to be in your file (I'm ignoring your hard-coded value of 78 lines), you can't create a string[] of the correct size up front.

Instead, you could start with a collection of strings:

var list = new List<string>();

Change your loop to:

using (var sr = new StreamReader("a.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        list.Add(line);
    }
}

And then ask for a string array from your list:

string[] result = list.ToArray();

Update

Inspired by Cuong's answer, you can definitely shorten this up. I had forgotten about this gem on the File class:

string[] result = File.ReadAllLines("a.txt");

What File.ReadAllLines does under the hood is actually identical to the code I provided above, except Microsoft uses an ArrayList instead of a List<string>, and at the end they return a string[] array via return (string[]) list.ToArray(typeof(string));.

like image 100
Cᴏʀʏ Avatar answered Dec 28 '22 01:12

Cᴏʀʏ