Andrew
Andrew

Reputation: 245

Convert Generic List<string> to byte[ ]

Hi i need to convert a generic list to an byte[] but my code doesn't work Can anybody give me some hints?

Thanks!

List<string> lines = inputFile.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();

byte[] output = new byte[lines.Count];
Encoding enc = Encoding.UTF8;
int i = 0;

foreach (string item in lines)
{
   output[i] = enc.GetBytes(item);
   i++;
}

Upvotes: 2

Views: 7700

Answers (3)

Jon
Jon

Reputation: 437664

I am assuming that you don't want one big array that encodes all the contents of the file because if that is the case there's absolutely no need to split into lines first; that will only make your job harder. With that as a given:

You are using an array of bytes where you should be using an array of arrays of bytes, like this:

byte[][] output = new byte[lines.Count][];

In other words, output needs to have two dimensions: it has as many items as there are lines, and each of those items is itself an array with as many bytes as required to encode the contents of that line in UTF-8.

After you wrap your head around this, consider also using LINQ for a cleaner syntax:

var lines = /* ... */
var output = lines.Select(l => Encoding.UTF8.GetBytes(l)).ToArray();

Upvotes: 4

Dave Bish
Dave Bish

Reputation: 19646

var bytes = File
    .ReadLines(@"path")
    .Select(line => Encoding.UTF8.GetBytes(line));

foreach(var lineBytes in bytes)
{
    //DoStuffz
}

Upvotes: 0

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

Here is the code, Hope this helps

byte[] dataAsBytes = lines.SelectMany(s => Text.Encoding.UTF8.GetBytes(s))
  .ToArray();

Upvotes: 5

Related Questions