【问题标题】:Is it possible for StreamWriter to open different files?StreamWriter 是否可以打开不同的文件?
【发布时间】:2013-10-21 02:04:42
【问题描述】:

我已初始化StreamWriter 实例并将其与“MyFile.txt”相关联

System.IO.StreamWriter sw = new StreamWriter("MyFile.txt");

所以现在我可以将数据写入这个文件了

sw.Write("Hello, world!");

是否可以使用 相同 StreamWriter (sw) 实例打开 另一个 文件,例如:

sw.Reopen("MySecondFile");

还是没有/没有意义?

【问题讨论】:

  • 你想通过重用同一个流写入器实例来解决什么问题?
  • @knittl 我之前曾多次使用 c++ 的ifstreamofstream。因此,用相同的实例重新打开流的可能性对我来说似乎很明显。

标签: c# file stream


【解决方案1】:

查看the documentation on StreamWriter。将StreamWriter 与文件关联的唯一方法是在构造函数中。

所以,不,不可能通过第二个文件重复使用实例

【讨论】:

    【解决方案2】:

    使用StreamWriter,您需要创建一个新实例来写入另一个文件。

    【讨论】:

      【解决方案3】:

      只需创建一个新的 StreamWriter 实例:

      StreamWriter sw = new StreamWriter("MyFile.txt");
      sw.Write("Hello world!");
      sw.Close();
      sw = new StreamWriter("SecondFile");
      sw.Write("Goodbye world!");
      

      因此,从某种意义上说,这是毫无意义的,因为您可以廉价地创建新实例。旧实例最终会自动进行垃圾回收,因此您不必担心内存泄漏。

      【讨论】:

      • OP 知道如何使用新实例。 Is it possible to open another file with the same StreamWriter (sw) instance some way l
      • 但是有效的区别在哪里呢?他试图解决的问题是什么?部分问题也是“它毫无意义吗?”。
      • 没有注意到 is it senseless 的事情...撤销我的反对票。哦,我的投票被锁定了..!!
      • @BhushanFirake 也许根本没有有效的区别。但我曾多次使用 c++ 的ifstreamofstream。因此,用相同的实例重新打开流的可能性对我来说似乎很明显。
      • @BhushanFirake:我编辑了我的问题,以便对为什么重新开放毫无意义提供更多解释。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 2021-07-05
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多