tags:

views:

61

answers:

2

How to read from a file array of numbers? I mean, how to read chars from a file?

sorry for bad eng.

upd: yes, i can :) just: "1 2 3 4 5 6 7 8" and etc. I just do not know how to read chars from a file.

+1  A: 

If your file is not too large you can read it all into memory using for example ReadAllLines and then use TryParse to interpret the strings as integers. Here is some example code you could use as a starting point:

List<int> integers = new List<int>();
foreach (string line in File.ReadAllLines(path))
{
    foreach (string item in line.Split(' '))
    {
        int i;
        if (!int.TryParse(item, out i))
        {
            throw new Exception("Implement error handling here");
        }

        integers.Add(i);
    }
}

If you know that the file will always contain valid input you can simplify this slightly by using Parse instead of TryParse.

Mark Byers
The only answer I am gonna vote for handling exception. Good job!
Nayan
+3  A: 
string[] numbers = File.ReadAllText("yourfile.txt").Split(' ');

or you could convert these to integers:

int[] numbers = File
    .ReadAllText("yourfile.txt")
    .Split(' ')
    .Select(int.Parse)
    .ToArray();
Darin Dimitrov
Well, take care for the bad integers which may throw exception.
Nayan
There are cases where it's better to throw an exception to inform the user that there was something wrong while parsing the file rather than silently ignoring it. Of course this will entirely depend on the application requirements which haven't been detailed here.
Darin Dimitrov