写入文件时"无法访问文件"

ope*_*emi 2 c# text-editor streamwriter

我一直在研究记事本的克隆,我遇到了一个问题.当我尝试将文本框中的文本写入我创建的文件时,我得到了异常:

该进程无法访问文件'C:\ Users\opeyemi\Documents\b.txt',因为它正由另一个进程使用.

以下是我编写的代码.我真的很感激有关我接下来应该做什么的任何建议.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

xan*_*tos 6

你必须"保护"你的StremWriter使用( 读取写入)中using,如:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path))
{
    textWriter.Write(textEditor.Text);
}
Run Code Online (Sandbox Code Playgroud)

没有.Close()必要.

你不需要System.IO.File.Create(path);,因为它StreamWriter会为你创建文件(并Create()返回FileStream你在代码中保持打开的文件)

从技术上讲,你可以:

File.WriteAllText(path, textEditor.Text);
Run Code Online (Sandbox Code Playgroud)

这是一体化,并做一切(开放,写,关闭)

或者,如果您真的想使用StreamWriter和File.Create:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(System.IO.File.Create(path)))
{
    textWriter.Write(textEditor.Text);
}
Run Code Online (Sandbox Code Playgroud)

(有一个StreamWriter接受的构造函数FileStream)