Brett H
Brett H

Reputation: 47

Saving Stream.Write to existing .CSV file doesn't replace data, only adds to existing data. How do I only replace the data?

The following code is used to save a CSV string, however, if I save to an existing .CSV, instead of replacing the data, it only adds the new string to the data already there. How do I remedy this? Is it something inherent to how the Stream.Write function works, or is this an idiosyncrasy of Excel and .CSV?

SaveFileDialog dialog = new SaveFileDialog();

dialog.AddExtension = true;
dialog.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
dialog.FilterIndex = 1;
dialog.Title = "Save As";
dialog.InitialDirectory = "C:\\";
dialog.CheckPathExists = true;
dialog.DefaultExt = ".csv";
dialog.ValidateNames = true;

if (dialog.ShowDialog() == DialogResult.OK)
{
    StreamWriter myStream = new StreamWriter(dialog.FileName, true);
    myStream.Write(//Function which returns a CSV-formmatted string//);
    myStream.Close();
    OpenFile(dialog.FileName);
}

Upvotes: 1

Views: 4596

Answers (4)

abatishchev
abatishchev

Reputation: 100288

Pass the proper parameter to the constructor:

new StreamWriter(
    path: path
    append: false);

Upvotes: 0

In new StreamWriter(dialog.FileName, true) change true to false

Intellisence will tell you what your parameters are named as you type the function call, and it might give you a tooltip about what they mean. You should pay attention to that

I believe that simply typing new StreaWriter(dialog.FileName) will set append to false by default.

Upvotes: 0

Shai
Shai

Reputation: 25619

Set append to false, that way, StreamWriter will overwrite the file, rather than appending the data to it.

StreamWriter myStream = new StreamWriter(dialog.FileName, false);

Upvotes: 3

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

StreamWriter myStream = new StreamWriter(dialog.FileName, false);

http://msdn.microsoft.com/library/36b035cb%28v=vs.100%29

the second parameter (bool append), is well described :

append Type: System.Boolean Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

Upvotes: 5

Related Questions