[英]The filename, directory name, or volume label syntax is incorrect, File.Copy
[英]File.Copy error - C# - IOException The filename, directory name, or volume label
嘗試將目錄中的所有文件/目錄復制到我創建的新位置。 用戶在組合框中選擇要使用的“備份驅動器”,然后單擊備份桌面按鈕時,只需在該驅動器上創建一個備份目錄,然后將所有文件復制到該目錄中。
備份目錄已在驅動器上正確創建-但它命中的第一個文件啟動了一個錯誤。
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);
}
}
我得到錯誤:
IOException未處理。
文件名,目錄名稱或卷標簽語法不正確。
在“自動”窗口(VS2010)中,我看到位置設置正確:
destinationLocation =適當的目錄( C:\\ Backups-8-2016 \\ Desktop \\ )
文件=相應的第一個文件( C:\\ Users \\ myusername \\ Desktop \\ myshortcut.url )
我想念什么? 我擁有復制/粘貼/創建內容的所有權利,並且創建了用於存儲它的目錄-只是移動文件時出現問題。
從文檔https://msdn.microsoft.com/zh-cn/library/c6cfw35a(v=vs.110).aspx
第二個參數:目標文件的名稱。 這不能是目錄或現有文件。
您需要將文件名連接到該文件夾。
試試這個
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.