【问题标题】:Stream to write strings and byte[] arrays?流写入字符串和字节 [] 数组?
【发布时间】:2011-11-07 09:44:03
【问题描述】:

用于写入文件字符串和字节[] 数组的流类是什么? 如果文件不存在,则需要打开文件以追加或创建新文件。

using (Stream s = new Stream("application.log")
{
    s.Write("message")
    s.Write(new byte[] { 1, 2, 3, 4, 5 });
}

【问题讨论】:

    标签: c# .net stream io


    【解决方案1】:

    使用BinaryWriter-Class

    using (Stream s = new Stream("application.log")
    {
       using(var b = new BinaryWriter(s))
       {
        b.Write(new byte[] { 1, 2, 3, 4, 5 });
       }
    }
    

    或者正如 Tim Schmelter 建议的(谢谢)只是 FileStream:

    using (var s = new FileStream("application.log", FileMode.Append, FileAccess.Write)
    {
        var bytes = new byte[] { 1, 2, 3, 4, 5 };
        s.Write(bytes, 0, bytes.Length);
    }
    

    如果需要,这个会附加或创建文件,但 BinaryWriter 更好用。

    【讨论】:

    • 也谢谢你(至于快速反应......是的,较短/较慢的人得到了“回答”......想知道为什么?)
    • 从我的问题中可以看出,我不遵循该规则,但您可以尝试用简短的评论快速回答问题,然后稍后编辑它并提供更多详细信息,无论如何我投票了你也是:)
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      也许您的情况需要更简单的东西?

      File.WriteAllBytes("application.log", new byte[] { 1, 2, 3 });
      File.WriteAllLines("application.log", new string[] { "1", "2", "3" });
      File.WriteAllText("application.log", "here is some context");
      

      【讨论】:

        【解决方案4】:

        试试BinaryWriter。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-23
          • 2017-03-04
          • 1970-01-01
          • 2013-09-27
          • 1970-01-01
          相关资源
          最近更新 更多