Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<string> to byte array by lines using c#

Tags:

c#

I want to convert a list of string to an array of byte to store it in a sql table, then download the file.

In the code below, I just focus in the conversion part.

List<string> Items = new List<string>();
Items.Add("1 - Test 1");
Items.Add("2 - Test 2");
Items.Add("3 - Test 3");

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

Now, when I download that as a txt file the output is:

1 - Test12 - Test 23 - Test 3

How can I change my code in order to get each line of the List<string> in the downloaded file as the output below:

1 - Test 1
2 - Test 2
3 - Test 3
like image 222
Somebody Avatar asked Oct 16 '15 14:10

Somebody


2 Answers

You could add a newline in the query. essentially adding a newline byte between each one.

byte[] dataAsBytes = Items.SelectMany(s =>
System.Text.Encoding.UTF8.GetBytes(s + Environment.NewLine)).ToArray();
like image 175
Lewis Taylor Avatar answered Oct 22 '22 20:10

Lewis Taylor


You could concatenate new-line strings:

string fulltext = String.Join(Environment.NewLine, Items);
byte[] dataAsBytes = System.Text.Encoding.UTF8.GetBytes(fulltext);
like image 26
Tim Schmelter Avatar answered Oct 22 '22 19:10

Tim Schmelter