Writwick
Writwick

Reputation: 2163

How to fill a MemoryStream with 0xFF bytes?

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!

Upvotes: 3

Views: 3076

Answers (1)

dtb
dtb

Reputation: 217313

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);
}

Upvotes: 5

Related Questions