Convert MemoryStream to byte array in CSharp

Description

The following code shows how to convert MemoryStream to byte array.

Example


//from  ww w.ja va2s  .com


using System;
using System.IO;

public class MainClass
{
    public static int Main(string[] args)
    {
    MemoryStream myMemStream = new MemoryStream();
    myMemStream.Capacity = 256;

    for(int i = 0; i < 256; i++)
      myMemStream.WriteByte((byte)i);

    myMemStream.Position = 0;

    for(int i = 0; i < 256; i++)
      Console.Write(myMemStream.ReadByte());  
    Console.WriteLine();

    FileStream dumpFile = new FileStream("Dump.dat", FileMode.Create, FileAccess.ReadWrite);
    myMemStream.WriteTo(dumpFile);
    byte[] bytesinMemory = myMemStream.ToArray();
    myMemStream.Close();

    for(int i = 0; i < bytesinMemory.Length; i++)
      Console.Write(bytesinMemory[i]);

    return 0;
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip