64

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

Geoff Dalgas
  • 6,116
  • 6
  • 42
  • 58
Polaris
  • 3,643
  • 10
  • 50
  • 61
  • 3
    An object of type MemoryStream has the Property "ToArray()". There you get the byte[] – Tomtom Jan 21 '13 at 16:37
  • 1
    Will this help you http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream ? – Kaf Jan 21 '13 at 16:37
  • 2
    @yan.kun The closed original had only the first line when closed. He's added more info since, as well as - for some reason - posting this duplicate. – J. Steen Jan 21 '13 at 16:42

4 Answers4

169

How about:

byte[] bytes = fs.ToArray();
Gabe
  • 49,577
  • 28
  • 142
  • 181
5

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;
}
Tomtom
  • 9,087
  • 7
  • 52
  • 95
  • 3
    +1. note that using `using` instead of `Flush` is much safer. Also requires somewhat unusual code for MemoryStream to be accessible after Dispose - need to create MemoryStream before `using (ms)`... – Alexei Levenkov Jan 21 '13 at 16:50
3
byte[] ObjectToByteArray(Object obj)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(ms, obj);
        return ms.ToArray();
    }
}
Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93
1
    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;
    }
Snake
  • 41
  • 1
  • 4