2

I have been working on a clone of notepad and I have run into a problem. When I try to write the text in the textbox into a file which I create I get the exception:

The process cannot access the file 'C:\Users\opeyemi\Documents\b.txt' because it is being used by another process.

Below is the code I have written. I would really appreciate any advise on what I should do next.

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    SaveFileDialog TextFile = new SaveFileDialog();
    TextFile.ShowDialog();
  // this is the path of the file i wish to save
    string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),TextFile.FileName+".txt");
    if (!System.IO.File.Exists(path))
    {
        System.IO.File.Create(path);
        // i am trying to write the content of my textbox to the file i created
        System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path);
        textWriter.Write(textEditor.Text);
        textWriter.Close();
    }
}
4

1 回答 1

6

You must "protect" your StremWriter use (both read and write) in using, like:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path))
{
    textWriter.Write(textEditor.Text);
}

no .Close() necessary.

You don't need the System.IO.File.Create(path);, because the StreamWriter will create the file for you (and the Create() returns a FileStream that you keep open in your code)

Technically you could:

File.WriteAllText(path, textEditor.Text);

this is all-in-one and does everything (open, write, close)

Or if you really want to use the StreamWriter and the File.Create:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(System.IO.File.Create(path)))
{
    textWriter.Write(textEditor.Text);
}

(there is a StreamWriter constructor that accepts FileStream)

于 2013-08-22T10:48:06.613 回答