关于c#:如何将MemoryStream写入byte []

How can I write MemoryStream to byte[]

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Creating a byte array from a stream

我正在尝试在内存中创建文本文件并将其写入byte[]。我该怎么做?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}

但由于数据长度的原因,它不起作用


怎么样:

1
byte[] bytes = fs.ToArray();

尝试以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}


1
2
3
4
5
6
7
8
9
byte[] ObjectToByteArray(Object obj)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(ms, obj);
        return ms.ToArray();
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    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;
    }