54

可能重复:
从流中创建字节数组

我正在尝试在内存中创建文本文件并写入它byte[]。我怎样才能做到这一点?

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;
}

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

4

4 回答 4

144

怎么样:

byte[] bytes = fs.ToArray();
于 2013-01-21T16:37:38.190 回答
5

试试下面的代码:

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;
}
于 2013-01-21T16:39:51.137 回答
2
byte[] ObjectToByteArray(Object obj)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(ms, obj);
        return ms.ToArray();
    }
}
于 2013-01-21T16:38:21.890 回答
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;
    }
于 2013-01-21T16:46:40.893 回答