我一直在研究這一小部分代碼,雖然看起來微不足道,但仍然看不清楚問題出在哪裏。我的功能做了一件非常簡單的事情。打開一個文件,複製其內容,替換內部的字符串並將其複製回原始文件(然後在文本文件中進行簡單的搜索和替換)。 我真的不知道該怎麼做,因爲我在原始文件中添加行,所以我只是創建一個文件的副本,(file.temp)複製一份備份(file.temp),然後刪除原始文件文件(文件)並將file.temp複製到文件。 我在刪除文件時收到異常。 下面是示例代碼:System.IO.IOException:另一個進程使用的文件
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)
通常,這些錯誤來自未封閉的文件流,但我已經採取的照顧。我想我已經忘記了一個重要的步驟,但無法弄清楚在哪裏。 非常感謝你的幫助,
嘗試設置FileInfo對象傳遞將方法設爲null。 – TheVillageIdiot 2009-06-22 04:05:37