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…
Best Answer
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:
Change your loop to:
And then ask for a string array from your list:
Update
Inspired by Cuong's answer, you can definitely shorten this up. I had forgotten about this gem on the
File
class:What
File.ReadAllLines
does under the hood is actually identical to the code I provided above, except Microsoft uses anArrayList
instead of aList<string>
, and at the end they return astring[]
array viareturn (string[]) list.ToArray(typeof(string));
.