convert stream to byte array c# code example

Example 1: c# string to byte array

string author = "Mahesh Chand";  
// Convert a C# string to a byte array  
byte[] bytes = Encoding.ASCII.GetBytes(author);  

// Convert a byte array to a C# string. 
string str = Encoding.ASCII.GetString(bytes);

Example 2: c# byte array to stream

Stream stream = new MemoryStream(byteArray);

Example 3: c# store byte array as string

string bitString = BitConverter.ToString(bytes);

Example 4: c# write byte[] to stream

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

Example 5: c sharp stream to byte array

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}