如何将字符串加载到FileStream而不需要访问磁盘?

26
string abc = "This is a string";

我该如何将 abc 加载到 FileStream 中?

FileStream input = new FileStream(.....);

2
那不就是一个“MemoryStream”吗? - Yuck
1
必须使用文件流吗? - Mark Kram
2
听起来像是一道作业题,http://bytes.com/topic/c-sharp/answers/273281-loading-string-into-filestream - Mark Kram
3
为什么这听起来像是一份作业?因为它没有以“我的客户/老板想让我……”开头吗? - musefan
1
好的,我想我会使用内存流。 - Mennan
显示剩余3条评论
1个回答

29

使用MemoryStream代替...

MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc));

记住,MemoryStream(就像FileStream一样)在使用完毕后需要关闭。您可以将代码放在using块中,以使此过程更加容易...

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接