2

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++;
}
1
  • 1
    Define "doesn't work" please. Commented Jul 3, 2012 at 10:15

3 Answers 3

5

Here is the code, Hope this helps

byte[] dataAsBytes = lines.SelectMany(s => Text.Encoding.UTF8.GetBytes(s))
  .ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

This returns a single byte array for the whole file, and I don't think this is what the OP wants to do.
@ErenErsönmez It's hard to say for sure, but from the declaration of byte[] output it looks like that was the intent.
File.ReadAllBytes("path") is better - if this is what the op wants
@dasblinkenlight I could be wrong, but then it wouldn't make any sense to split the file into lines first :)
4

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();

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.