2015-10-13 224 views
1

我試圖通過編程將文件從桌面複製到USB驅動器。但是,試圖運行該代碼時,我在歌廳一個錯誤,說明該路徑的那部分無法找到:從'計算機'訪問USB驅動器

if (dr == DialogResult.Yes) 
{ 
    string selected = comboBox1.GetItemText(comboBox1.SelectedItem); 

    string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
    string filefolder = @"\UpgradeFiles"; 

    string fileLocation = filePath + filefolder; 

    if (!Directory.Exists(fileLocation)) 
    { 
     Directory.CreateDirectory(fileLocation); 
    } 

    else if (Directory.Exists(fileLocation)) 
    { 
     DirectoryInfo di = new DirectoryInfo(fileLocation); 

     FileInfo[] fileList = di.GetFiles(); 
     foreach (FileInfo file in fileList) 
     { 
      string DrivePath = Environment.GetFolderPath(
       Environment.SpecialFolder.MyComputer); 
      string CopyToDrive = comboBox1.Text; 

      file.CopyTo(DrivePath + CopyToDrive, false); 
     } 
    } 
} 

組合框包含所選驅動器盤符。當我試圖添加「computer \ driveletter」時,我會接近這個錯誤嗎?

+0

是不是沒有人爲此付出時間 –

+0

@CallumBradbury非常好。 – Sean

+0

我這樣認爲:首先,在合併路徑時不要使用Path + Path,使用Path.Combine,這會減少出錯的機率,並且很可能成爲這裏的問題 –

回答

2

你File.CopyTo(DrivePath + CopyToDrive,假的)應該是:

File.CopyTo(CopyToDrive + File.Name, false); 

但有一點語法糖就像使用Path.Combine或的String.Format而不是 「+」。

問題是File.CopyTo需要目錄和文件名的結束位置,當你只是提供目錄。這可以在方法調用的文檔中看到:https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx

+0

完美的工作。非常感謝。 – Sean

+0

沒問題,我想最後我確實有時間了 –

+0

因爲這是在我的foreach循環中,它會從該位置複製所有文件,對嗎? – Sean