Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to write long type array to binary file

I have a long array. How to write this array to a binary file? Problem is that if I convert it into byte array some values are changed.

The array is like:

long array = new long[160000];

Give some code snippet.

like image 831
Royson Avatar asked Sep 14 '26 12:09

Royson


2 Answers

The BinaryFormatter will be the easiest.

Also valuetypes (I assume this is what you mean by long), serializes very efficiently.

like image 183
leppie Avatar answered Sep 17 '26 00:09

leppie


var array = new[] { 1L, 2L, 3L };
using (var stream = new FileStream("test.bin", FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new BinaryWriter(stream))
{
    foreach (long item in array)
    {
        writer.Write(item);
    }
}
like image 40
Darin Dimitrov Avatar answered Sep 17 '26 01:09

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!