Search code examples
c#streamwriter

StreamWriter doesn't seem to be doing anything?


I have a program that reads a CSV, and replaces its values.

I use the same file, it reads the file, extracts the data, populates a DataTable, then reconstructs the data to be re-written into the CSV with no issues, but when I check the CSV, it's empty.

It doesn't matter if I use the same file, or create a new file, they all come up empty.

Here is my Write Method:

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(','));
    }
}

Again, the program has no problems with the data, or the files, it just doesn't write to the file.


Solution

  • You need to close the file and make sure it flushes to disk

    The easiest way is wrap it in a using statment

    using (StreamWriter writer = new StreamWriter(sfd.FileName))
    {
    
        //do stuff here
        ...
        ...
    
    } // this closes and flushes the file to disk
    

    Some additional reading

    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.

    Exmaple

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

    Update

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

    A StreamWriter opening with those arguments is backed by a FileStream, it will not save unless it has auto-flushed or you flush it. This will happen when you close, and close will happen when you dispose. Rule of thumb, if it is disposable, always use a using statement