我一直在研究这段看似微不足道的小代码,但我仍然无法真正看出问题出在哪里。我的函数做了一件非常简单的事情。打开一个文件,复制其内容,替换其中的字符串并将其复制回原始文件(然后在文本文件中进行简单的搜索和替换)。我真的不知道该怎么做,因为我正在向原始文件添加行,所以我只是创建文件的副本,(file.temp)复制也是备份(file.temp)然后删除原始文件(文件)并将file.temp复制到文件中。删除文件时出现异常。这是示例代码:
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)
通常这些错误来自未关闭的文件流,但我已经处理好了。我想我忘记了一个重要的步骤,但不知道在哪里。非常感谢您的帮助,