Share via


Beware of MemoryStream.GetBuffer() method

How about controlling [moving slides back and forth] powerpoint presentation that runs in laptop using a windows mobile phone? I wanted to develop this application for fun. The requirement that I set is as follows

  • Mobile phone should contact the laptop using bluetooth 
  • Move next / Move previous of slides should be controlled by Mobile phone left and right buttons.
  • After moving the slide in the laptop, the mobile phone should show the latest slide in its screen.

I have designed the application in such a way that this application consists of two parts. One systray application that sits in laptop and another compact framework application that runs in mobile phone.  The server part  - systray application should watch a bluetooth serialport for any input. The mobile phone client sends the moveNext / MovePrevious command along with the mobile phone screen size. The server part moves the slide by using sendkeys, captures the screen image, resize it and then send it back to mobile client.

Here I have faced the issue of 4KB limit. So the client has to interact manytimes with the server to get the full image.  Initially I have used MemoryStream.GetBuffer() method to get the byte array from the memory stream that contains screen image dump, chunk it and then send it to client. But with this way, I never got the image at the client. After spending some time with " ONLINE MSDN " I have found that I should make use of MemoryStream.ToArray() method. The online MSDN describes the following -

  "Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory".

I could not find this information in desktop version of MSDN Library. I believe  ToArray() method should be used limitedly as this method copies data from the memory each and every time it gets called. For example, the following line of code

slPort.Write(memStream.ToArray(), offset, memStream.ToArray().Length - offset);

can be written like

byte[] bytArr = memStream.ToArray();
slPort.Write(bytArr, offset, bytArr.Length - offset);

hmmm... Im fine tuning this application now.  Will post it free for the readers once it is completed.

Comments

  • Anonymous
    May 24, 2012
    How about slPort.Write(memStream.GetBuffer(), offset, (int)memStream.Length - offset); ?