Skip to main content
 首页 » 编程设计

c#之从 SaveFileDialog 创建、写入和打开文本文件

2024年02月20日12开发

我正在显示一个 SaveFileDialog,当单击“确定”时,我正在创建新文件,向其中写入一些默认内容,然后尝试通过 SaveFileDialog 的 OpenFile() 方法打开它。然而,当我调用 OpenFile() 时,文件的内容被删除了。

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() } ); 
} 

有人可以解释为什么会发生这种情况以及我需要做什么才能成功打开新创建的文件吗?

请您参考如下方法:

根据 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.