2011-03-11 49 views
1
string fName = Path.GetFileName(tempPaths[z]);  
if (!File.Exists(subAch + fName)) 
          { 

           File.Move(tempPaths[z], subAch + fName); 
           Console.WriteLine("moved!!! from " + tempPaths[z] + " tooooo "); 


          } 

tempPaths是一個包含所有圖像文件路徑的列表。例如./images/image4.jpg獲取文件名並將其移動

subAch是一個目錄字符串。

我想獲取文件的文件名,然後將它們移動到另一個目錄。但隨着上面的代碼我不斷收到錯誤:文件正在被其他進程使用。

有沒有辦法得到文件名並移動它們?我已經試過fileStream但被它弄糊塗了。

請指教。

謝謝!

+0

請原諒我的錯誤。 – meAtStackOverflow 2011-03-14 02:53:43

回答

0

文件被另一個進程正在使用意味着。有人/某事已經在使用該文件,因此無法移動它。你總是可以抓住錯誤並移動其他所有東西?

+0

謝謝Vincent 當我運行Just Path類時,一切都很好。僅當我嘗試將Path類和File Class放在一起時發生此錯誤。 我在想也許路徑類getFileName鎖定文件。無論如何解鎖它? – meAtStackOverflow 2011-03-12 03:54:18

2

你的代碼應該可以正常工作。你只需要弄清誰在鎖定文件。 我會把代碼放在try-catch塊中的if塊中來處理鎖定的文件。 我也會推薦你使用Path.Combine而不是dir +文件。有一件事:你正在檢查subAch + tempPaths [z]是否存在,但你正在複製到不同的位置; subAch + fName。

+0

THanks Ole-Brun tempPaths [z]是原始文件的來源。 subAch + fname是目的地。 如果我添加subAch + tempPaths [z]整個事情將是錯誤的。 你能指導我如何我能夠檢查是否阻止? – meAtStackOverflow 2011-03-12 03:52:51

+0

我不確定檢查文件是否在代碼中被阻止是有意義的。您看到該文件在您檢查時可能未被阻止,但在嘗試移動該文件時可能會再次被阻止。你應該檢查你的代碼,看看你是否可能在某處阻止了這些文件,或者使用一個單獨的工具(如Sysinternals)來找出誰在阻止這些文件。 – 2011-03-12 09:34:51

0

我使用非理想的方式來獲取文件名並將文件移動到另一個地方。

tempPaths.AddRange(Directory.GetFiles(rawStorePath, filter, SearchOption.AllDirectories)); 

上面的代碼獲取文件夾集中所有文件的所有目錄。結果是這樣的。 tempPaths是一個List。

"./images/glass_numbers_5.jpg" 
"./images/G.JPG" 
"./images/E.JPG" 
"./images/F.JPG" 
"./images/glass_numbers_0.jpg" 
"./images/C.JPG" 
"./images/B.JPG" 
"./images/A.JPG" 
"./images/D.JPG" 
"./images/glass_numbers_7.jpg" 

然後我用循環來抓取文件名。

for (int i = 0; i < tempPaths.Count; i++) 
       { 
        //Getting the original names of the images 
        int pLength = rawStorePath.Length; 
        string something = tempPaths[i].Remove(0, pLength); 
        if (!_tfileName.ContainsKey(tempPaths[i])) 
        { _tfileName.Add(tempPaths[i], something); } 
       } 

rawStorePath是目標路徑例如爲:./images/ TEMPPATH [I]例如路徑:./images/G.JPG

所以隨着長度我刪除的字母,並獲得文件名。

請指教我一個理想的方式來做到這一點,如果有的話。

謝謝!

相關問題