How can I write MemoryStream to byte[]

C#Stream

C# Problem Overview


> Possible Duplicate:
> Creating a byte array from a stream

I'm trying to create text file in memory and write it byte[]. How can I do this?

public byte[] GetBytes()
{
    MemoryStream fs = new MemoryStream();
    TextWriter tx = new StreamWriter(fs);

    tx.WriteLine("1111");
    tx.WriteLine("2222");
    tx.WriteLine("3333");

    tx.Flush();
    fs.Flush();

    byte[] bytes = new byte[fs.Length];
    fs.Read(bytes,0,fs.Length);

    return bytes;
}

But it does not work because of data length

C# Solutions


Solution 1 - C#

How about:

byte[] bytes = fs.ToArray();

Solution 2 - C#

Try the following code:

public byte[] GetBytes()
{
MemoryStream fs = new MemoryStream();
TextWriter tx = new StreamWriter(fs);

tx.WriteLine("1111");
tx.WriteLine("2222");
tx.WriteLine("3333");

tx.Flush();
fs.Flush();
byte[] bytes = fs.ToArray();
return bytes;
}

Solution 3 - C#

byte[] ObjectToByteArray(Object obj)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(ms, obj);
        return ms.ToArray();
    }
}

Solution 4 - C#

    public byte[] GetBytes()
    {
        MemoryStream fs = new MemoryStream();
        TextWriter tx = new StreamWriter(fs);

        tx.WriteLine("1111");
        tx.WriteLine("2222");
        tx.WriteLine("3333");

        tx.Flush();
        fs.Flush();

        fs.Position = 0;

        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, bytes.Length);

        return bytes;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPolarisView Question on Stackoverflow
Solution 1 - C#GabeView Answer on Stackoverflow
Solution 2 - C#TomtomView Answer on Stackoverflow
Solution 3 - C#Priyank ThakkarView Answer on Stackoverflow
Solution 4 - C#SnakeView Answer on Stackoverflow