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...
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();
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));
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With