2

我有一个long数组。如何将此数组写入二进制文件?问题是如果我将它转换成byte数组,一些值会改变。

数组是这样的:

long array = new long[160000];

给出一些代码片段。

4

3 回答 3

6

BinaryFormatter 将是最简单的。

还有 valuetypes (我假设这就是你所说的 long 的意思),非常有效地序列化。

于 2009-12-08T09:40:17.300 回答
4
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);
    }
}
于 2009-12-08T09:43:00.710 回答
1

价值观是如何变化的?并且一个long数组可以很快的复制到一个byte数组中,不需要序列化。

 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();
        }
于 2009-12-08T15:00:57.800 回答