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