Question

J'ai un tableau de long. Comment écrire ce tableau dans un fichier binaire? Le problème est que si je le convertir en tableau byte certaines valeurs sont modifiées.

Le tableau est comme:

long array = new long[160000];

Donnez un peu extrait de code.

Était-ce utile?

La solution

Le BinaryFormatter sera le plus facile.

Aussi types de valeur (je suppose que c'est ce que vous entendez par long), sérialisés de façon très efficace.

Autres conseils

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

Comment sont les valeurs modifiées? Et un tableau de temps peut être copié dans un tableau d'octets très rapidement, pas besoin de sérialisation.

 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();
        }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top