需要帮助从小字节数组创建一个大数组

时间:2012-10-12 11:51:14

标签: c# bytearray

我收到了以下代码:

    byte[] myBytes = new byte[10 * 10000];
    for (long i = 0; i < 10000; i++)
    {
        byte[] a1 = BitConverter.GetBytes(i);
        byte[] a2 = BitConverter.GetBytes(true);
        byte[] a3 = BitConverter.GetBytes(false);

        byte[] rv = new byte[10];
        System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
        System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
        System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);
    }

一切都按预期运作。我试图转换这段代码,所以所有内容都会被写入myBytes,但后来我意识到,我使用了很长时间,如果它的值会更高,那么int.MaxValue施法会失败。 怎么能解决这个问题?

另一个问题是,因为我不想在内存中创建一个非常大的bytearray,我怎么能将它发送到我的.WriteBytes(path, myBytes);函数?

2 个答案:

答案 0 :(得分:2)

如果建议的最终目的地是文件:然后更直接地写入文件,而不是在内存中缓冲:

using (var file = File.Create(path)) // or append file FileStream etc
using (var writer = new BinaryWriter(file))
{
    for (long i = 0; i < 10000; i++)
    {
        writer.Write(i);
        writer.Write(true);
        writer.Write(false);
    }
}

在您的情况下执行此的理想方法可能是在序列化它们时依次将单个BinaryWriter实例传递给每个对象(不要打开和关闭文件每个对象)。

答案 1 :(得分:1)

为什么不在处理它们时将Write()写出来而不是转换为大量缓冲区,或者至少使用较小的缓冲区?

相关问题