C# how to write long type array to binary file

10,648

Solution 1

The BinaryFormatter will be the easiest.

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

Solution 2

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

Solution 3

How are the values changed? And an array of long can be copied into an array of byte very quickly, no need for serialization.

 static void Main(string[] args) {

            System.Random random = new Random();

            long[] arrayOriginal = new long[160000];
            long[] arrayRead = null;

            for (int i =0 ; i < arrayOriginal.Length; i++) {
                arrayOriginal[i] = random.Next(int.MaxValue) * random.Next(int.MaxValue);
            }

            byte[] bytesOriginal = new byte[arrayOriginal.Length * sizeof(long)];
            System.Buffer.BlockCopy(arrayOriginal, 0, bytesOriginal, 0, bytesOriginal.Length);

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {

                // write 
                stream.Write(bytesOriginal, 0, bytesOriginal.Length);

                // reset
                stream.Flush();
                stream.Position = 0;

                int expectedLength = 0;
                checked {
                    expectedLength = (int)stream.Length;
                }
                // read
                byte[] bytesRead = new byte[expectedLength];

                if (expectedLength == stream.Read(bytesRead, 0, expectedLength)) {
                    arrayRead = new long[expectedLength / sizeof(long)];
                    Buffer.BlockCopy(bytesRead, 0, arrayRead, 0, expectedLength);
                }
                else {
                    // exception
                }

                // check 
                for (int i = 0; i < arrayOriginal.Length; i++) {
                    if (arrayOriginal[i] != arrayRead[i]) {
                        throw new System.Exception();
                    }
                }
            }

            System.Console.WriteLine("Done");
            System.Console.ReadKey();
        }
Share:
10,648
Royson
Author by

Royson

Updated on June 14, 2022

Comments

  • Royson
    Royson almost 2 years

    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.

  • Darin Dimitrov
    Darin Dimitrov over 14 years
    @leppie, I agree with you. I've performed some measurements and using BinaryFormatter as you suggested performs better.