0

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);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Brett H
  • 37
  • 1
  • 8

4 Answers4

4
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.

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • Well, I feel a little silly for not looking at StreamWriter's definition first, but thank you for the answer. :) – Brett H Jul 11 '12 at 16:09
2

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);
Shai
  • 25,159
  • 9
  • 44
  • 67
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.

0

Pass the proper parameter to the constructor:

new StreamWriter(
    path: path
    append: false);
abatishchev
  • 98,240
  • 88
  • 296
  • 433