文件正由另一个进程使用

时间:2016-06-10 15:52:17

标签: c# file-io

我在C#中遇到了这个代码被执行的问题 没有通过,它给我一个错误“文件被另一个进程使用”(或类似)。 我已经尝试在Stack上寻找答案,但我无法将所有内容整合在一起。 我试图在那里插入一些代码(就像他们说的那样),但只是给我更多的错误。 请提前帮助,非常感谢!

以下是我当前的代码=>

// let's create example.py
string path = @"C:\example.py";
var stream = new FileStream(path, FileAccess.Read);
var reader = new StreamReader(stream);
if (!File.Exists(path)) {
    File.Create(path);
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# code to insert into target file");
} else if (File.Exists(path)) {
    System.IO.File.WriteAllText(@"C:\example.py", string.Empty); // clear contents
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# more code to insert into example.py");
}

这是我的原始代码(没有修复尝试)=>

// let's create example.py
string path = @"C:\example.py";
if (!File.Exists(path)) {
    File.Create(path);
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# code to insert into target file");
} else if (File.Exists(path)) {
    System.IO.File.WriteAllText(@"C:\example.py", string.Empty); // clear contents
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# more code to insert into example.py");
}

3 个答案:

答案 0 :(得分:1)

我发现这完全有效 - >

// let's create example.py
const string path = @"C:\example.py";
using (FileStream fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
using (TextWriter sw = new StreamWriter(fileStream))
{
    {
        sw.WriteLine("First line");
        sw.WriteLine("Second line");
        sw.Close();
    }
}

答案 1 :(得分:0)

请参阅:File being used by another process after using File.Create()

只需删除File.Create并直接使用:

using (StreamWriter sw = new StreamWriter(path, true))
{
    // ...
}

答案 2 :(得分:0)

您必须关闭FileStream返回的File.Create

  File.Create(path).Close();

有关详细信息,请参阅MDSN

https://msdn.microsoft.com/en-us/library/d62kzs03(v=vs.110).aspx

然而,更好的方法是写入文件:

  if (File.Exists(path))
    File.AppendAllText(path, "# more code to insert into example.py");
  else 
    File.AppendAllText(path, "# code to insert into target file");  

甚至

File.AppendAllText(path, File.Exists(path) 
  ? "# more code to insert into example.py"
  : "# code to insert into target file");