【问题标题】:Why no line is writen in output using StreamWriter为什么使用 StreamWriter 在输出中没有写入任何行
【发布时间】:2015-04-21 06:55:02
【问题描述】:

我在使用 StreamWriter 时遇到问题,只是找不到我做错了什么。

String line, new_line;
using (StreamReader sr = new StreamReader(txtFilePath.Text))
{
    using (StreamWriter sw = new StreamWriter(txtResultFolder.Text.ToString() + "\\" + "NEW_trimmed_file" + ".csv", true))
    {
        while ((line = sr.ReadLine()) != null)
        {
            new_line = line.TrimEnd();
            MessageBox.Show(new_line);
            sw.WriteLine(new_line);
        }
    }
}

我使用了 MessageBox.Show(new_line),只是为了确保我有一个可供 StreamWriter 写入的值,但在结果文件中我找不到任何东西。 作为附加信息,我有一个文本,每行都有空格(很多空格),我正在制作另一个文件,其行与第一行相同,但没有空格。 任何提示为什么 StreamWriter 实际上没有写入目标文件?

非常感谢,

【问题讨论】:

  • 手动指定路径是否有效?
  • 写入文件的大小是多少? 0 字节还是 1 或 2 字节?如果是 1 或 2 个字节我怀疑你写了一个空行。
  • @Dion V:这不相关。当我在调试中运行它时,我可以看到为“line”字符串加载的值(来自第一个文件),我也可以从我的位置看到名为“NEW_trimmed_file.csv”的文件。但实际上没有写任何行。
  • 您是否在最后一个 '}' 处暂停了调试器?
  • @Ako:这就是我放 messagebox.show 的原因,只是为了确保我打算写的行有一些数据。这是因为对话框显示了它。该文件有 0 个字节

标签: c# streamreader


【解决方案1】:

但在结果文件中我找不到任何东西

如果您希望您的StreamWriter 在处置前立即写入缓冲区,您需要调用Flush()

string line, new_line;

using (StreamReader sr = new StreamReader(txtFilePath.Text))             
using (StreamWriter sw = new StreamWriter(txtResultFolder.Text.ToString() +
                                          "\\" + "NEW_trimmed_file" + ".csv", true))
{
   while ((line = sr.ReadLine()) != null)
   {
      new_line = line.TrimEnd();
      MessageBox.Show(new_line);
      sw.WriteLine(new_line);
   }
   sw.Flush();
}

【讨论】:

  • 您无需致电Flush()StreamWriterDispose() 上自动刷新。
  • @Yuval:非常非常感谢!有效。最初我在 sw.WriteLine(new_line) 之后尝试了 sw.Flush() 命令,但没有任何效果,仍然是一个空文件。当你写的那样使用它时,它工作得很好。再次感谢。
  • @Downvoter - 我很想知道你认为这个答案有什么问题。
  • @Yuval - 这是不正确的信息。您无需致电Flush。查看来自Joel CoehoornJon Skeet 的帖子。
  • 关闭StreamWriter时不需要调用Flush。正如@JonTirjan 所说,这是错误的。 FWIW,我不是反对者。
【解决方案2】:

读写文件的方式要短得多。只需使用 File.ReadAllLines() 和 File.WriteAllLines()

var content = File.ReadAllLines(txtFilePath.Text)

File.WriteAllLines(txtResultFolder.Text.ToString(), content);

我对@9​​87654323@ 的命名有点困惑。这个路径是文件夹吗?这个TextBox的具体内容是什么?

【讨论】:

  • 代码只是我的 winform 应用程序的一个示例。 txtResultFolder 是用户选择的目标文件夹。 StreamWriter 的目的地是动态生成的。我不能使用 ReadAllLines 和 WriteAllLines,因为我需要“修剪”的原始文件有大约 2200 万行,因此只有 StreamWrite 和 StreamRead 可以工作(尝试了你所说的但服务器崩溃)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多