Mono Class Library: System.IO.MemoryStream Overview | Members

System.IO.MemoryStream.GetBuffer Method

Returns the array of unsigned bytes from which this stream was created. [Edit]

public virtual byte[] GetBuffer ()

Returns

The byte array from which the current stream was created, or the underlying array if a byte array was not provided to the System.IO.MemoryStream constructor during construction of the current instance. [Edit]

Exceptions

TypeReason
UnauthorizedAccessExceptionThe current instance was not created with a publicly visible buffer. [Edit]

Remarks

To create a System.IO.MemoryStream instance with a publicly visible buffer use the default constructor, System.IO.MemoryStream( byte [], int, int, bool, true) or System.IO.MemoryStream(int ) constructor.

If the current stream is resizable, multiple calls to this method do not return the same array if the underlying byte array is resized between calls. For additional information, see MemoryStream.Capacity .

Note: This method works when the System.IO.MemoryStream is closed.

Operation
As described above.

[Edit]

Example

The following example demonstrates that two calls to the MemoryStream.GetBuffer method on a resizable stream do not return the same array if the underlying byte array is reallocated.

C# Example
using System;
using System.IO;

public class MemoryStreamTest {
   public static void Main() {

      MemoryStream ms = new MemoryStream(10);

      byte[] a = ms.GetBuffer();
      byte[] b = ms.GetBuffer();

      //Force reallocation of the underlying byte array.
      ms.Capacity = 10240;    
      byte[] c = ms.GetBuffer();


      if(Object.ReferenceEquals(a, b))
         Console.WriteLine("a and b represent the same instance.");
      else
         Console.WriteLine("a and b represent the different instances.");

      if(Object.ReferenceEquals(a, c))
         Console.WriteLine("a and c represent the same instance.");
      else
         Console.WriteLine("a and c represent the different instances.");

   }
}

The output is

a and b represent the same instance.
a and c represent the different instances.

Requirements

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0