简体   繁体   中英

Write byte array block by block using FileStream.Write without ArgumentException

I have 256 KB byte array. I need to write it to file block by block(I should try 10 different values between 512 and 1024 bytes). I wrote a bit of C# code and my problem is that at the end of my FileStream.Write loop I am breaking the bounds of the array.

static void Main()
    {
        var sourceArray = new byte[256 * 1024];
        new Random().NextBytes(sourceArray);
        var blockSizes =new[]
        {
            512,
            512 + 512/10,
            512 + (512/10)*2,
            512 + (512/10)*3,
            512 + (512/10)*4,
            512 + (512/10)*5,
            512 + (512/10)*6,
            512 + (512/10)*7,
            512 + (512/10)*8,
            1024
        };
        foreach (var bs in blockSizes)
            using (var fs = new FileStream(bs.ToString(), FileMode.Create))
                for (var i = 0; i < sourceArray.Length; i += bs)
                    fs.Write(sourceArray, i, bs);
    }

Here is the exception which I don't know how to deal with:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

By the way, using ready-made methods like File.WriteAllBytes or File.WriteAllText is unacceptable.

You just need to make sure your last write only writes as many bytes as are left in the file, which is sourceArray.Length - i :

static void Main()
{
    var sourceArray = new byte[256 * 1024];
    new Random().NextBytes(sourceArray);
    var blockSizes = new[]
    {
        512,
        512 + 512/10,
        512 + (512/10)*2,
        512 + (512/10)*3,
        512 + (512/10)*4,
        512 + (512/10)*5,
        512 + (512/10)*6,
        512 + (512/10)*7,
        512 + (512/10)*8,
        1024
    };
    foreach (var bs in blockSizes)
        using (var fs = new FileStream("C:\\tmptmp\\" + bs.ToString(), FileMode.Create))
            for (var i = 0; i < sourceArray.Length; i += bs)
                fs.Write(sourceArray, i, Math.Min(bs, sourceArray.Length - i));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM