【问题标题】:"Cannot access file" when writing to file写入文件时“无法访问文件”
【发布时间】:2013-08-25 01:23:24
【问题描述】:

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

进程无法访问文件'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();
    }
}

【问题讨论】:

  • “我非常感谢任何关于我下一步应该做什么的建议” - 不要在没有在网络上搜索您收到的错误的情况下打开问题。这里每隔两天就会问一个关于File.Create() 锁定文件的问题。

标签: c# text-editor streamwriter


【解决方案1】:

您必须在using 中“保护”您的StremWriter 使用(both readwrite),例如:

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

不需要.Close()

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

技术上你可以:

File.WriteAllText(path, textEditor.Text);

这是一体式的,可以做所有事情(打开、写入、关闭)

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

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

(有一个接受FileStreamStreamWriter 构造函数)

【讨论】:

  • 感谢您的建议。它现在可以工作,但我仍然想知道为什么当我使用 .close 时它没有。当我尝试 using 语句时它也没有工作。
  • @opeyemi 这个:`System.IO.File.Create(path);` 创建一个文件并保持打开状态。其次是:new System.IO.StreamWriter(path) 创建一个文件并保持打开状态。你看到问题了吗?两条指令试图打开文件。 File.Create 不是“创建一个零字节文件并关闭它”。它是“创建一个文件并保持打开状态”。不是void Create(path),而是FileStream Create(path)。从技术上讲,您可以拥有File.Create(path).Close();,但它没有用。
  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多