如何在不转到磁盘的情况下将字符串加载到FileStream中?

Men*_*ano 19 c# filestream

string abc = "This is a string";
Run Code Online (Sandbox Code Playgroud)

如何将abc加载到FileStream中?

FileStream input = new FileStream(.....);
Run Code Online (Sandbox Code Playgroud)

mus*_*fan 22

使用MemoryStream代替......

MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc));
Run Code Online (Sandbox Code Playgroud)

记住,当你完成它之后,需要关闭一个MemoryStream(就像一个FileStream).您始终可以将代码放在使用块中以使其更容易...

using(MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc)))
{
   //use the stream here and don't worry about needing to close it
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您的字符串是Unicode而不是ASCII,则可能需要在转换为Byte数组时指定此字符串.基本上,Unicode字符占用2个字节而不是1.如果需要,将添加填充(例如,0x00 0x61在unicode中0x61="a" ,在ASCII ="a"中)