System.IO.IOException:另一个进程使用的文件

我一直在研究这段似乎微不足道的小代码,但我仍然无法确定问题出在哪里。 我的function很简单。 打开文件,复制其内容,替换内部的字符串并将其复制回原始文件(然后在文本文件中进行简单的搜索和替换)。 我真的不知道怎么做,因为我在原始文件中添加了行,所以我只创建了一个文件副本,(file.temp)副本也备份(file.temp)然后删除原始文件(文件)并将file.temp复制到文件。 我在删除文件时遇到exception。 以下是示例代码:

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) { Boolean result = false; FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); StreamReader streamreader = file.OpenText(); String originalPath = file.FullName; string input = streamreader.ReadToEnd(); Console.WriteLine("input : {0}", input); String tempString = input.Replace(extractedMethod, modifiedMethod); Console.WriteLine("replaced String {0}", tempString); try { sw.Write(tempString); sw.Flush(); sw.Close(); sw.Dispose(); fs.Close(); fs.Dispose(); streamreader.Close(); streamreader.Dispose(); File.Copy(originalPath, originalPath + ".old", true); FileInfo newFile = new FileInfo(originalPath + ".tmp"); File.Delete(originalPath); File.Copy(fs., originalPath, true); result = true; } catch (Exception ex) { Console.WriteLine(ex); } return result; }` 

和相关的例外

 System.IO.IOException: The process cannot access the file 'E:\mypath\myFile.cs' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) at callingMethod.modifyFile(FileInfo file, String extractedMethod, String modifiedMethod) 

通常这些错误来自未封闭的文件流,但我已经处理过了。 我想我已经忘记了一个重要的步骤,但无法弄清楚在哪里。 非常感谢您的帮助,

听起来像外部进程(AV?)锁定它,但你不能首先避免这个问题?

 private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) { try { string contents = File.ReadAllText(file.FullName); Console.WriteLine("input : {0}", contents); contents = contents.Replace(extractedMethod, modifiedMethod); Console.WriteLine("replaced String {0}", contents); File.WriteAllText(file.FullName, contents); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } } 

我意识到我有点迟了,但迟到总比没有好。 我最近遇到了类似的问题。 我使用XMLWriter随后更新XML文件并收到相同的错误。 我找到了干净的解决方案:

XMLWriter使用基础FileStream来访问修改后的文件。 问题是,当您调用XMLWriter.Close()方法时,基础流不会被关闭并锁定文件。 您需要做的是使用设置实例化XMLWriter并指定您需要关闭该底层流。

例:

 XMLWriterSettings settings = new Settings(); settings.CloseOutput = true; XMLWriter writer = new XMLWriter(filepath, settings); 

希望能帮助到你。

我能说出最好的代码。 我会启动Sysinternals进程资源管理器并找出文件打开的内容。 它可能很适合Visual Studio。

在遇到这个错误并且没有在Web上找到任何让我正确的内容之后,我想我会添加另一个获得此exception的原因 – 即File Copy命令中的源路径和目标路径是相同的。 我花了一段时间来弄清楚它,但如果源和目标路径指向同一个文件,那么在某处添加代码可能有助于抛出exception。

祝好运!

它对我有用。

这是我的测试代码。 测试运行如下:

 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { FileInfo f = new FileInfo(args[0]); bool result = modifyFile(f, args[1],args[2]); } private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) { Boolean result = false; FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); StreamReader streamreader = file.OpenText(); String originalPath = file.FullName; string input = streamreader.ReadToEnd(); Console.WriteLine("input : {0}", input); String tempString = input.Replace(extractedMethod, modifiedMethod); Console.WriteLine("replaced String {0}", tempString); try { sw.Write(tempString); sw.Flush(); sw.Close(); sw.Dispose(); fs.Close(); fs.Dispose(); streamreader.Close(); streamreader.Dispose(); File.Copy(originalPath, originalPath + ".old", true); FileInfo newFile = new FileInfo(originalPath + ".tmp"); File.Delete(originalPath); File.Copy(originalPath + ".tmp", originalPath, true); result = true; } catch (Exception ex) { Console.WriteLine(ex); } return result; } } } C:\testarea>ConsoleApplication1.exe file.txt padding testing input :  replaced String  

您是否有机会运行实时防病毒扫描程序? 如果是这样,您可以尝试(暂时)禁用它以查看是否正在访问您尝试删除的文件。 (Chris建议使用Sysinternals进程探索器是一个很好的建议)。

试试这个:它在任何情况下都有效,如果文件不存在,它会创建它然后写入它。 如果已经存在,没有问题会打开并写入:

  using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite)) { fs.close(); } using (StreamWriter sw = new StreamWriter(@"File.txt")) { sw.WriteLine("bla bla bla"); sw.Close(); } 

创建文件后,必须强制流释放资源:

 //FSm is stream for creating file on a path// System.IO.FileStream FS = new System.IO.FileStream(path + fname, System.IO.FileMode.Create); pro.CopyTo(FS); FS.Dispose(); 
  System.Drawing.Image FileUploadPhoto = System.Drawing.Image.FromFile(location1); FileUploadPhoto.Save(location2); FileUploadPhoto.Dispose();