Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create, write to and open a text file from SaveFileDialog

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?

like image 296
Stewart Alan Avatar asked Oct 25 '25 23:10

Stewart Alan


1 Answers

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.

like image 121
Sam Axe Avatar answered Oct 27 '25 14:10

Sam Axe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!