我正在尝试以编程方式将文件从桌面复制到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 :(得分:2)
你的File.CopyTo(DrivePath + CopyToDrive,false)应为:
File.CopyTo(CopyToDrive + File.Name, false);
但有一些语法糖,比如使用Path.Combine或String.Format而不只是“+”。
问题是,当您只提供目录时,File.CopyTo需要结束位置的目录AND文件名。这可以在此处方法调用的文档中看到:https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx