0

when i trying to read text file into list of byte i use this code:

FileStream File = new FileStream(filename, FileMode.Open);
List<byte> file = new List<byte>();

using(StreamReader sr = new StreamReader(File))
{
   string myString = sr.ReadToEnd();
   file.Add(Convert.ToByte(myString));
}

appearing this error("Input string was not in a correct format"),I'm trying to solve the problem with another code but appear the same error.

my file contain this data: 5 1 0 6 1 1 6 1 2 6 3 0 1 5 0 1 2 1 1 5 1 0 6 1 1 6 1 2 6 3 0 1 5 1 2 6 3 0 1 5 0 3 1 3 6 5 2 1 2 3 6 5 3 3 2 1 6 5 0 1 1 3 1 3 1 3 5 5 0 1 1 3 1 3 0 0 0 3 3 2 1 3 0 0 0 0 0 1 1 3 1 3 0

and i want this result list=[5,1,0,6,1,1,.....]

Layan
  • 19
  • 1
  • 1
  • 6

2 Answers2

2

Your myString is list of values so you'll need to split it first and convert each value like so:

file = myString.Split(' ').Select(n => Convert.ToByte(n)).ToList();

or

file.AddRange(myString.Split(' ').Select(n => Convert.ToByte(n)))
dkozl
  • 32,814
  • 8
  • 87
  • 89
0

You need to Split your strings

string myString = sr.ReadToEnd();
foreach(var part in myString.Split(Environment.NewLine.ToCharArray()))
{
  foreach (var part2 in part.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
  {
    file.Add(Convert.ToByte(part2));
  }
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184