我有一个long
阵列。如何将这个数组写入二进制文件? 问题是,如果我把它转换成byte
阵列的一些值的变化。C#如何写长型数组的二进制文件
阵列是这样的:
long array = new long[160000];
给一些代码段。
我有一个long
阵列。如何将这个数组写入二进制文件? 问题是,如果我把它转换成byte
阵列的一些值的变化。C#如何写长型数组的二进制文件
阵列是这样的:
long array = new long[160000];
给一些代码段。
的BinaryFormatter的将是最容易的。
也值类型(我想这是你长的意思),序列化非常有效。
同意二进制格式化程序。 – 2009-12-08 10:14:25
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);
}
}
这将是非常缓慢的,但它的工作:) – leppie 2009-12-08 09:44:43
@leppie,我同意你的看法。我已经执行了一些测量,并且按照您的建议使用'BinaryFormatter'执行得更好。 – 2009-12-08 15:06:18
值是如何变化的?一个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-08 10:19:04