Create, write to and open a text file from SaveFileDialog

Stewart Alan picture Stewart Alan · Sep 5, 2012 · Viewed 11.9k times · Source

I am displaying a SaveFileDialog and when OK is clicked I am creating new file, writing some default content to it and then attempting to Open it via the OpenFile() method of the SaveFileDialog. However, the moment I call OpenFile() the content of the file are deleted.

SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML files (*.xml)|*.xml";
saveFileDialog.RestoreDirectory = true;

if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    // First Event Creates file and writes default content to it - works ok 
    NewFileCreated( this, new FileCreatedEventArgs() { Template = Template.BBMF, FilePath = saveFileDialog.FileName } );
    // Second Event clears file content as soon as saveFileDialog.OpenFile() called
    FileLoaded( this, new FileLoadedEventArgs() { FileStream = saveFileDialog.OpenFile() } );
}

Can someone explain why this happens and what I need to be doing to successfully Open the newly created file?

Answer

Sam Axe picture Sam Axe · Sep 5, 2012

According to MSDN, SaveFileDialog.OpenFile()

Caution

For security purposes, this method creates a new file with the selected name and opens it with read/write permissions. This can cause unintentional loss of data if you select an existing file to save to. To save data to an existing file while retaining existing data, use the File class to open the file using the file name returned in the FileName property.