简体   繁体   English

写入文件时“无法访问文件”

[英]“Cannot access file” when writing to file

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. 该进程无法访问文件'C:\\ Users \\ opeyemi \\ Documents \\ b.txt',因为该文件正在被另一个进程使用。

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

You must "protect" your StremWriter use ( both read and write ) in using , like: 你必须“保护”你StremWriter使用( 读写 )中using ,如:

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

no .Close() necessary. 不需要.Close()

You don't need the System.IO.File.Create(path); 您不需要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) ,因为StreamWriter会为您创建文件(并且Create()返回您在代码中保持打开状态的FileStream

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: 或者,如果您确实要使用StreamWriter和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 ) (有一个StreamWriter构造函数接受FileStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM