为什么使用 StreamWriter 没有在输出中写入任何行

Why no line is writen in output using StreamWriter

我在使用 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 实际上没有写入目标文件的任何提示?

非常感谢,

but in the resulted file I cannot find anything

如果您希望 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();
}

有一种更短的方式来读写文件。只需使用 File.ReadAllLines() 和 File.WriteAllLines()

var content = File.ReadAllLines(txtFilePath.Text)

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

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