4

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...

whoone
  • 533
  • 3
  • 7
  • 16

1 Answers1

15

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));.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • @whoone: See my updated answer. There's a nice shortcut that will save you a few lines of code. – Cᴏʀʏ Sep 28 '12 at 14:00
  • I don't find System.IO.File in the add reference. Do you have the solution? – whoone Sep 29 '12 at 10:05
  • `File` is part of the CLR. You just need to import `System.IO`. – Cᴏʀʏ Sep 29 '12 at 19:54
  • ReadAllLines throws an error stating that the file is in use for me. I had to go back to using a streamreader with File.Open for my solution. Anyone have any idea how to use "FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite" paramters that you have in File.Open with File.ReadAllLines? – Trevor Panhorst Apr 12 '18 at 18:47
  • `File.ReadAllLines` opens a `FileStream` with the parameters `FileMode.Open, FileAccess.Read, FileShare.Read`. Using a `StreamReader` as you have described would be one valid solution. – Cᴏʀʏ Apr 12 '18 at 20:58