StreamWriter 似乎没有做任何事情?

StreamWriter doesn't seem to be doing anything?

我有一个读取 CSV 文件并替换其值的程序。

我使用同一个文件,它读取文件、提取数据、填充数据表,然后重建数据以重新写入 CSV,没有任何问题,但是当我检查 CSV 时,它是空的。

无论我使用同一个文件,还是创建一个新文件,它们都是空的。

这是我的写入方法:

void RewriteCSV(DataTable table)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
    sfd.FilterIndex = 1;
    sfd.RestoreDirectory = true;

    // If no File is selected, the program ends.
    if (sfd.ShowDialog() != DialogResult.OK)
    {
        return;
    }
    StreamWriter writer = new StreamWriter(sfd.FileName);

    string line = "";

    foreach (DataColumn col in table.Columns)
    {
        line += col.ColumnName + ",";
    }
    writer.WriteLine(line.TrimEnd(','));

    foreach (DataRow row in table.Rows)
    {
        line = "";
        foreach (string s in row.ItemArray)
        {
            line += s + ",";
        }
        writer.WriteLine(line.TrimEnd(','));
    }
}

同样,程序对数据或文件没有问题,它只是不写入文件。

您需要关闭文件并确保它刷新到磁盘

最简单的方法是将其包装在 using 语句中

using (StreamWriter writer = new StreamWriter(sfd.FileName))
{

    //do stuff here
    ...
    ...

} // this closes and flushes the file to disk

一些补充阅读

StreamWriter.Flush Method ()

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

FileStream.Flush Method ()

Clears buffers for this stream and causes any buffered data to be written to the file.

StreamWriter.Close Method ()

Closes the current StreamWriter object and the underlying stream. You must call Close to ensure that all data is correctly written out to the underlying stream. Following a call to Close, any operations on the StreamWriter might raise exceptions. If there is insufficient space on the disk, calling Close will raise an exception.

using Statement

Provides a convenient syntax that ensures the correct use of IDisposable objects.

例子

using (StreamWriter writer = new StreamWriter("important.txt"))
{
    writer.Write("Word ");
    writer.WriteLine("word 2");
    writer.WriteLine("Line");
}

更新

Oh, so it doesn't "save" until you close the stream?

使用这些参数的 StreamWriter 开头由 FileStream 支持,除非它已自动刷新或您刷新它,否则它不会保存。这将在您关闭时发生,而关闭将在您处置时发生。根据经验,如果它是一次性的,请始终使用 using 语句