【问题标题】:How do I load a string into a FileStream without going to disk?如何在不进入磁盘的情况下将字符串加载到 FileStream 中?
【发布时间】:2012-02-12 10:53:34
【问题描述】:
string abc = "This is a string";

如何将 abc 加载到 FileStream 中?

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

【问题讨论】:

  • 那不就是MemoryStream吗?
  • 您为什么要这样做?为什么不使用 MemoryStream 之类的东西?
  • 必须是文件流吗?
  • 听起来像是一道作业题,bytes.com/topic/c-sharp/answers/…
  • @MarkKram:为什么听起来像家庭作业?因为它不是以“我的客户/老板要我……”开头的?

标签: c# filestream


【解决方案1】:

改用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,您可能需要在转换为 Byte 数组时指定它。基本上,一个 Unicode 字符占用 2 个字节而不是 1 个。如果需要,将添加填充(例如,0x00 0x61 = "a" 在 unicode 中,而在 ASCII 中 0x61 = "a")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 2011-03-31
    • 2010-10-11
    相关资源
    最近更新 更多