2009-06-22 22 views
23

我一直在研究這一小部分代碼,雖然看起來微不足道,但仍然看不清楚問題出在哪裏。我的功能做了一件非常簡單的事情。打開一個文件,複製其內容,替換內部的字符串並將其複製回原始文件(然後在文本文件中進行簡單的搜索和替換)。 我真的不知道該怎麼做,因爲我在原始文件中添加行,所以我只是創建一個文件的副本,(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) 

通常,這些錯誤來自未封閉的文件流,但我已經採取的照顧。我想我已經忘記了一個重要的步驟,但無法弄清楚在哪裏。 非常感謝你的幫助,

+1

嘗試設置FileInfo對象傳遞將方法設爲null。 – TheVillageIdiot 2009-06-22 04:05:37

回答

23

聽起來像一個外部進程(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; 
    } 
} 
+13

+1全複雜配置關閉,刷新streamreader thingy(不使用使用語句等..)讓我發抖。它把一個簡單的問題變成了一個難以維持的混亂局面。 – 2009-06-22 04:29:47

+0

非常感謝您使用這種方法,我同意這種方式比我的原始方法更清晰。 這解決了我的問題! – srodriguez 2009-06-22 05:25:57

+0

謝謝你。我一直在尋找類似情況的答案。我已經關閉了XMLWriter,但它仍然給我錯誤。一旦我將這個陳述放在try-catch中,它就不會再給我提供錯誤了。 – illinoistim 2013-12-12 20:55:38

5

代碼工作作爲最好的,我可以告訴。我會激發Sysinternals process explorer並找出什麼是打開文件。它很可能是Visual Studio。

3

它爲我工作。

這是我的測試代碼。測試運行如下:

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 :   <style type="text/css"> 
     <!-- 
     #mytable { 
      border-collapse: collapse; 
      width: 300px; 
     } 
     #mytable th, 
     #mytable td 
     { 
      border: 1px solid #000; 
      padding: 3px; 
     } 
     #mytable tr.highlight { 
      background-color: #eee; 
     } 
     //--> 
     </style> 
replaced String   <style type="text/css"> 
     <!-- 
     #mytable { 
      border-collapse: collapse; 
      width: 300px; 
     } 
     #mytable th, 
     #mytable td 
     { 
      border: 1px solid #000; 
      testing: 3px; 
     } 
     #mytable tr.highlight { 
      background-color: #eee; 
     } 
     //--> 
     </style> 
3

您是否正在運行實時防病毒掃描程序? 如果是這樣,你可以嘗試(暫時)禁用它,看看是否是什麼訪問您要刪除的文件。 (Chris建議使用Sysinternals進程管理器是一個好主意)。

18

我意識到我有點晚了,但遲到還是比從未好。我最近有類似的問題。我使用XMLWriter來隨後更新XML文件並收到相同的錯誤。我發現這個乾淨的解決方案:

XMLWriter使用基礎FileStream訪問修改後的文件。問題是,當您調用XMLWriter.Close()方法時,基礎流不會關閉並鎖定文件。您需要做的是使用設置實例化XMLWriter並指定您需要關閉的基礎流。

例子:

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

希望它能幫助。

4

過這個錯誤去 - 這是把我的權利在網絡上沒有找到任何東西,我想我會添加其他原因讓這個異常 - 即在文件拷貝命令的源和目標路徑是相同的。我花了一段時間才弄明白,但如果源和目標路徑指向同一個文件,則可能會在某處添加代碼以引發異常。

祝你好運!

2

試試這個:它在任何情況下工作,如果文件不存在,它會創建它,然後寫入它。如果已經存在,沒有問題它會打開和寫入:

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(); 
} 
-1
System.Drawing.Image FileUploadPhoto = System.Drawing.Image.FromFile(location1); 
           FileUploadPhoto.Save(location2); 
           FileUploadPhoto.Dispose(); 
0

創建一個文件後,必須強制流釋放資源:

//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(); 
相關問題