How to fill a MemoryStream with 0xFF bytes?

做~自己de王妃 提交于 2019-12-22 18:47:16

问题


I have a MemoryStream which is created from a File at runtime.

Then the MemoryStream is edited and some bytes are removed.

Now I have to maintain a Constant Filesize so I have to fill the MemoryStream with 0xFF bytes..

What is the Fastest way to Do this Operation?

I know, that I always can loop through the MemoryStream sizes and add 0xFF's but I need to know a faster and more efficient way to do it!


回答1:


If you have many bytes to write to the stream, it may be more efficient to write a array rather than each byte individually:

static void Fill(this Stream stream, byte value, int count)
{
    var buffer = new byte[64];
    for (int i = 0; i < buffer.Length; i++)
    {
        buffer[i] = value;
    }
    while (count > buffer.Length)
    {
        stream.Write(buffer, 0, buffer.Length);
        count -= buffer.Length;
    }
    stream.Write(buffer, 0, count);
}


来源:https://stackoverflow.com/questions/10570142/how-to-fill-a-memorystream-with-0xff-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!