read text file into array

  • Thread starter Thread starter mhodkin
  • Start date Start date
M

mhodkin

What is the best way to fill an array (or other container) with values
from a text file containing numbers in a simple column, especially when
one doesn't know how many values the text file list contains?
 
What is the best way to fill an array (or other container) with values
from a text file containing numbers in a simple column, especially when
one doesn't know how many values the text file list contains?

As with most things in .NET, there are several ways to do this but, assuming
the following:

1) you're using v2 of the Framework

2) each line contains only one "column" of data

3) each line of data is convertible into an integer

this should do it for you:

using System.IO;

List<int> lstData = new List<int>();
StreamReader objSR = File.OpenText(<filespec>);
string strLineIn = String.Empty;
while ((strLineIn = objSR.ReadLine()) != null)
{
lstData.Add(Convert.ToInt32(strLineIn));
}

Obviously, replace <filespec> with the actual path to your text file.

If the numerical data can't be converted into integers, you'll have to amend
the List<T> declaration and the numerical conversion accordingly.

[Apologies for the use of pseudo-quasi-not-quite-Hungarian notation... ;-)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top