简体   繁体   中英

MemoryStream cannot be expanded…refactoring from FileStream to MemoryStream or similar

I have a problem refactoring a chunk of code. I vaguely understand the problem but a little more insight and or explanation would be very helpful to my understanding and resolving the problem.

First the original chunk of code:

FileStream fS = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
Int64 fSLength = fS.Length;
Int64 remainingNotFulEncDecBlock = fSLength % 1;
fS.Seek(0, SeekOrigin.End);
Int64 nrBytesToAdd = 1 - remainingNotFulEncDecBlock;

Byte fillByte = (Byte)'$';

  for (Int32 i = 0; i < nrBytesToAdd - 1; i++)
    fS.WriteByte(fillByte);
    fS.WriteByte((Byte)nrBytesToAdd);
    fSLength = fS.Length;
    fS.Close();

The only purpose to the refactor is that we no longer have a physical file to open. Instead we provide a byte[] .

Here is my refactored code:

MemoryStream fS = new MemoryStream(_data);
Int64 fSLength = fS.Length;
Int64 remainingNotFulEncDecBlock = fSLength % 1;
fS.Seek(0, SeekOrigin.End);
Int64 nrBytesToAdd = 1 - remainingNotFulEncDecBlock;

Byte fillByte = (Byte)'$';
  for (Int32 i = 0; i < nrBytesToAdd - 1; i++)
    fS.WriteByte(fillByte);
    fS.WriteByte((Byte)nrBytesToAdd);
    fSLength = fS.Length;
    fS.Close();

The code above produces the error MemoryStream cannot be expanded on the line

fS.WriteByte((Byte)nrBytesToAdd);

Originally I had to Google the error and read up. This now makes sense as the memory stream has been set to a specific size. What I am unclear on is how should I proceed. Do I create another MemoryStream object that is NOT set to a specific size thus allowing me to do something like:

MemoryStream ms = new MemoryStream();
ms.WriteByte((Byte)nrBytesToAdd);

My reading of this technique indicates this will be less performant than initializing a MemoryStream to a specified byte[] however I don't know of (can't find) another way to expand MemoryStream dynamically. One plus is that now and in the foreseen future the byte[] coming in will be very small so while slower probably won't make a drastic impact on performance.

You can use the MemeoryStream constructor that takes an initial capacity.

MemoryStream fS = new MemoryStream(_data.Length);

This will set up the internal byte array of that size so the memory stream doesn't have to keep expanding the array each time it hits it's size limit. It will allow you to add bytes to the memory stream. While not as effective as just having a static byte[] size it's probably the next best thing.

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