如何将MemoryStream写入byte []

Pol*_*ris 33 c# stream

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

我正在尝试在内存中创建文本文件并编写它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;
}
Run Code Online (Sandbox Code Playgroud)

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

Gab*_*abe 100

怎么样:

byte[] bytes = fs.ToArray();
Run Code Online (Sandbox Code Playgroud)


Tom*_*tom 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;
}
Run Code Online (Sandbox Code Playgroud)

  • +1。请注意,使用“using”而不是“Flush”更安全。还需要一些不寻常的代码才能在 Dispose 之后访问 MemoryStream - 需要在 `using (ms)` 之前创建 MemoryStream... (3认同)