简体   繁体   English

File.Copy错误-C#-IOException文件名,目录名或卷标签

[英]File.Copy error - C# - IOException The filename, directory name, or volume label

Trying to copy all files/directories inside a directory to a new location that I create. 尝试将目录中的所有文件/目录复制到我创建的新位置。 Users select the 'backup drive' to work with to in a combobox, then when they click the backup desktop button it simply creates a backup directory on that drive and copies all the files into that directory. 用户在组合框中选择要使用的“备份驱动器”,然后单击备份桌面按钮时,只需在该驱动器上创建一个备份目录,然后将所有文件复制到该目录中。

The backup directory gets created on the drive appropriately - but the first file it hits it kicks off an error. 备份目录已在驱动器上正确创建-但它命中的第一个文件启动了一个错误。

private void backupDesktopButton_Click(object sender, EventArgs e)
{
     //set the destionationLocation to the selectedDrive
     string selectedDrive = backupDriveCombo.SelectedItem.ToString();
     string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\";
     if (!Directory.Exists(destinationLocation))
     {
         Directory.CreateDirectory(destinationLocation);
     }

     string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

     string[] fileList = Directory.GetFiles(desktopFolder);
     foreach (string file in fileList)
     {
         //move the file
         File.Copy(file, destinationLocation);
     }
}

I get the error: 我得到错误:

IOException was unhandled. IOException未处理。

The filename, directory name, or volume label syntax is incorrect. 文件名,目录名称或卷标签语法不正确。

In the 'Autos' window (VS2010) I see the locations are set correctly: 在“自动”窗口(VS2010)中,我看到位置设置正确:

destinationLocation = the appropriate directory ( C:\\Backups-8-2016\\Desktop\\ ) destinationLocation =适当的目录( C:\\ Backups-8-2016 \\ Desktop \\

file = the appropriate first file ( C:\\Users\\myusername\\Desktop\\myshortcut.url ) 文件=相应的第一个文件( C:\\ Users \\ myusername \\ Desktop \\ myshortcut.url

What am I missing? 我想念什么? I have all rights to be able to copy/paste/create things and the directory to store it gets created - just a problem moving the file. 我拥有复制/粘贴/创建内容的所有权利,并且创建了用于存储它的目录-只是移动文件时出现问题。

From the documentation https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx 从文档https://msdn.microsoft.com/zh-cn/library/c6cfw35a(v=vs.110).aspx

the second parameter: The name of the destination file. 第二个参数:目标文件的名称。 This cannot be a directory or an existing file. 这不能是目录或现有文件。

you need to concat the filename to the folder. 您需要将文件名连接到该文件夹​​。

Try something like this 试试这个

string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
    string targetFile = Path.Combine(destinationLocation, Path.GetFileName(file));
    if (File.Exists(targetFile)) File.Delete(targetFile);
    File.Copy(file, targetFile);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM