TPlant
TPlant

Reputation: 453

How to read from file to list in one line?

I'm trying to read numbers separated with spaces from file.

using (var streamReader = new StreamReader("save.txt", Encoding.UTF8))
{
    list = streamReader.ReadToEnd().Split(new char[] { ' ' }, 1).Select(n => int.Parse(n)).ToList();
}

When I try to run this code I get System.FormatException at int.Parse(n) with n beeing string containing content of the whole file. As long as I understand why I'm getting this exception I have no idea why Split() method is not working?

Upvotes: 0

Views: 124

Answers (3)

Steve
Steve

Reputation: 216293

There is a 1 into the list of chars used for splitting the string, remove it an it works.

list = streamReader.ReadToEnd()
       .Split(new char[] { ' ' })
       .Select(n => int.Parse(n)).ToList();

If you leave the 1 then the result of Split would be an array of just one element.
For example, if you have this input string

string input = "1 2 3 4 5";
string[] result = input.Split(new char[] {' '}, 1);

result will be an array like this

result.Length == 1; // true
result[0] == "1 2 3 4 5"; // true

Of course passing the string

int.Parse("1 2 3 4 5")

gives the error above.

Upvotes: 2

Gary Walker
Gary Walker

Reputation: 9134

I always liked File.ReadAllLines() -- its goes back to .Net 2.0 and I don't have to write any code of my onw.

Upvotes: 1

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

You have an unnecessary 1 parameter in Split(new char[] { ' ' }, 1) which means only one element will be returned. It is also safer to use RemoveEmptyEntries option. You can also simplify reading from file with help of File.ReadAllText:

File.ReadAllText("path")
    .Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(n => int.Parse(n))
    .ToList();

Upvotes: 4

Related Questions