Create, write to and open a text file from SaveFileDialog

13,075

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.

Share:
13,075
Stewart Alan
Author by

Stewart Alan

Updated on June 27, 2022

Comments

  • Stewart Alan
    Stewart Alan almost 2 years

    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?

  • Stewart Alan
    Stewart Alan over 11 years
    Yes, this is what i did. Created the File in the NewFileCreated event and then opened it using the File Class in the FileLoaded event
  • Sam Axe
    Sam Axe over 11 years
    So, If you want to open the file without destroying the existing contents you need to open it via the FileStream class and pass in FileMode.Append to the appropriate ctor.