2011-03-01 122 views
7

重命名在C#中的文件:文件重命名問題?

File.Move(source,Destination); 
      File.Delete(source); 

它成功執行,當我嘗試如何以往任何時候都再次重命名的文件時,系統給出了這樣的例外: ,因爲它正在使用的進程無法訪問該文件另一個過程。 我無法找到這在哪裏使用?當我進一步調試錯誤時,它顯示我的類名是在IIS的w3wp.exe進程中。接下來我應該做什麼? 越來越

foreach (string folder in folder) 
{ 
FileSystemItem item = new FileSystemItem(); 
DirectoryInfo di = new DirectoryInfo(folder); 
item.Name = di.Name; 
item.FullName = di.FullName; 
item.Path = path + "\\" + item.Name; 
item.CreatedDate = di.CreationTime; 
item.IsFolder = true; 
item.Extension = "folder"; 
listFolder.Add(item); 
} 
docList = CreatXmllist(listFolder); 
return docList 

我這是怎麼得到的文件夾列表,然後將其返回到XML。然後在文件夾中我得到的文件,當我點擊它

現在得到的圖像:這是代碼

public xml (string path, List<l> one) 
    { 

     List<T> tt = new List<T>(); 
     List<T> SessionList = new List<T>(); 
     string[] files = Directory.GetFiles(HttpContext.Current.Request.PhysicalApplicationPath + path); 

     foreach (string file in files) 
     { 
      FileSystemItem item = new FileSystemItem(); 
      FileInfo i = new FileInfo(file); 
      string a = i.LastWriteTime.ToString(); 
      var thumbnails = from a in b where a.Name == fi.Name select t; 

      if (fi.Name != "a") 
       if (t.Count() == 0) 
       { 
        r session r = new r(); 
        r.aName = fi.aName; 
        SessionList.Add(r); 
        fi.Exists; 
       } 
       else 
        t.Add((T)t.First()); 

     } 
+3

爲什麼在重新命名後刪除源代碼? – GolezTrol 2011-03-01 09:52:02

+0

@ Golez Trol:因爲我移動了文件(就像複製)並將其重命名爲新名稱。 – safi 2011-03-01 09:53:44

+0

我認爲沒有必要的第二行 – hallie 2011-03-01 09:55:12

回答

2

你並不需要調用File.Delete作爲重命名的一部分,你如果你做了副本,會需要它。

+0

我刪除了file.delete(源),仍然它給我的錯誤:( – safi 2011-03-01 09:55:12

1

嘗試使用FileShare枚舉器。然後嘗試用monesharing打開文件,關閉句柄,如果沒有異常,則可以移動文件。

http://msdn.microsoft.com/de-de/library/system.io.fileshare.aspx

它包含的方法讀,寫等

+0

'FileStream s2 =新的FileStream(名稱,FileMode.Open,FileAccess.Read,FileShare.Read);'有一個參數fileshare.read,那麼它將可能刪除,如果它已經是可能的打開另一個用戶? – safi 2011-03-01 09:58:06

+0

是的,這應該工作。 – 2011-03-01 10:00:15

+0

好的謝謝,我想這樣做,然後我必須在file.move(source,dest)中指定s2,所以它會像file.move( s2,destination)? – safi 2011-03-01 10:02:25

1

創建一個FileInfo例如,您可以將其重命名不止一次。

FileInfo file = new FileInfo(source); 
file.MoveTo(destination); 

// execute more code 

file.MoveTo(destination2) 
+0

彼得範Kekem:它仍然不工作:( – safi 2011-03-01 10:18:19

+0

你能請張貼關於例外的更多細節? (Stacktrace,內部異常,可能來自事件查看器) – 2011-03-01 10:52:02

+0

我可以得到一些關於這個問題的幫助嗎? – safi 2011-03-01 11:28:19