2015-10-13 118 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