2016-07-31 100 views
0

我試圖使用File.Copy()函數將一個圖像從一個位置複製到另一個位置,但它使進程無法訪問異常,任何一個可以請幫忙在這個波紋是代碼塊。我已經附上截圖的例外。該進程無法訪問該文件,因爲它正在被另一個進程使用。##

private void btnUpload_Click(object sender, EventArgs e) 
{ 
    string SourcePath; 
    string RootDrive; 
    string DestPath; 
    string fileName; 
    fileName = ""; 
     try 
     { 
      OpenFileDialog ofd = new OpenFileDialog(); 
      ofd.Title = "Select Image to Upload"; 
      ofd.Filter = "Jpg|*.jpg|Jpge|*.jpge|Gif|*.gif"; 
      ofd.FileName = null; 
      if (ofd.ShowDialog() != DialogResult.Cancel) 
      { 
       fileName = ofd.FileName; 

      } 
      ofd.Dispose(); 
      DestPath = Directory.GetCurrentDirectory() + @"\Uploads\PropertyImages\"; 
       string destFile = System.IO.Path.Combine(DestPath, fileName); 

       if (!System.IO.Directory.Exists(DestPath)) 
       { 
        System.IO.Directory.CreateDirectory(DestPath); 
       } 
       System.IO.File.Copy(fileName, destFile, true);         

     } 
     catch (Exception ae) 
     { 
      MessageBox.Show(ae.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 

enter image description here

+0

一些其他程序正在使用的文件。就這麼簡單。你有沒有在另一個程序副本中打開文件?其他一些程序? – siride

+0

此外,如果您將文件上傳到當前位置的相同位置,則會出現該錯誤。確保您的源路徑和目標路徑不同。 – siride

+0

@siride否該文件未被其他程序使用,並且是兩個路徑都不相同 – Shashikant

回答

1

這可能是因爲您正試圖將文件複製到自身。您撥打電話Combine(),只是返回fileName。更改以下行:

string destFile = System.IO.Path.Combine(DestPath, fileName); 

string destFile = System.IO.Path.Combine(DestPath, System.IO.Path.GetFileName(fileName)); 
+0

非常感謝這工作:) – Shashikant

+0

@Shashikant - 如果這個答案解決了你的問題,請務必標記爲Accepted(點擊綠色的選中標記),以便其他人如果他們稍後訪問,就知道這是正確的解決方案。 :) – Tommy

+0

@seairth完成,你可以請解釋像什麼函數GetFileName()實際上做。 – Shashikant

相關問題