Problem to save content C#

Asked

Viewed 122 times

1

I’m trying to make a replica of the notepad, in the part of saving content in richTextBox1.Text I’m having the problem:

System.IO.Ioexception:"Process cannot access file 'file path' 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);
}
  • Post the code you use to open the text file

  • In case I haven’t done yet to open, just wanted to save msm. Then I would do the rest

  • But to make this mistake you have to be with some stream of the open file. Surely there’s more code there. There’s no helping you without seeing the troublesome part.

  • The rest is just Empty Event.

  • 1

    You are opening the file fileDialog.OpenFile();and does not close so it remains open. tries fileDialog.Close(); before the Dispose()

  • You are opening the file with fileDialog.OpenFile(); for no reason whatsoever in that function, and it is not closing it, hence the error. The fileDialog.Dispose(); does not close the file.

Show 1 more comment

1 answer

1


A suggestion would be you 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, it will be easier to both read the code and will not worry about calling the Close method at the end of the process.

As our colleague has said, the problem may have occurred for a number of reasons, but I will highlight two:

  1. The file itself may be open without calling Openfiledialog, ie open file by yourself.

  2. Maybe you forgot to call the Close() method in Openfiledialog.

Then try using when you create an Openfiledialog, Savefiledialog, and other objects that require the Close() method to be called.

  • Thanks, I redid everything and now it’s working right

Browser other questions tagged

You are not signed in. Login or sign up in order to post.