Problem to save C # content [closed]

0

I'm trying to do a replica of Notepad, in the part of saving the content in richTextBox1.Text I'm having the problem:

  

System.IO.IOException: "The process can not access the 'file path' file because it is already being used by another process.

private void salvarComoToolStripMenuItem_Click(object sender, EventArgs e)      
{
    SaveFileDialog fileDialog = new SaveFileDialog();
    fileDialog.Filter = "|*.txt";
    fileDialog.ShowDialog();
    fileDialog.OpenFile();
    string path = fileDialog.FileName;
    fileDialog.Dispose();
    richTextBox1.SaveFile(path);
}
    
asked by anonymous 11.10.2017 / 19:23

1 answer

0

One suggestion would be to use the using clause. Example:

 private void salvarComoToolStripMenuItem_Click(object sender, EventArgs e)      
 {
    using(SaveFileDialog fileDialog = new SaveFileDialog())
    {
        fileDialog.Filter = "|*.txt";
        fileDialog.ShowDialog();
        fileDialog.OpenFile();
        string path = fileDialog.FileName;
        fileDialog.Dispose();
        richTextBox1.SaveFile(path);
    }
}

Using this form will make both the code reading easier and will not bother to call the Close method at the end of the process.

As our colleague spoke, the problem may have occurred for n reasons, but I will highlight two:

The file itself can be opened without calling OpenFileDialog, that is, open file by yourself.

  • Maybe you forgot to call the Close () method in OpenFileDialog.

  • Then try to use the using when you create an object of type OpenFileDialog, SaveFileDialog and other objects that require the Close () method to be called in the end.

        
    12.10.2017 / 02:12