2016-12-25 85 views
2

我想從桌面移動一個文件到一個名爲「文本文件」的目錄,但每次我嘗試它時都會給我這個錯誤。如何將文件移動到目錄而不是替換文件?

附加信息:目標文件「C:\ Users \ Developer \ Documents \ Textfiles」是一個目錄,而不是文件。

現在我知道,使用

File.Copy(fileName, targetPath); 

將是錯誤的,這就是我使用的是現在,它有兩個參數,第一個是yopu要複製的文件,第二個是在檔案取代?糾正我,如果我錯了第二個參數。

不管怎麼說,我試過System.IO.Directory.Move(fileName, destFile);,但這差不多給了我同樣的錯誤。

這兩個參數非常簡單,只有兩個由路徑組成的字符串。

string fileName = filePath.ToString(); 
string targetPath = @"C:\Users\Developer\Documents\Textfiles"; 

什麼是將fileName傳輸到targetPath的正確方法?

回答

2

你需要指定目標文件名。

string fileOnly = System.IO.Path.GetFileName(fileName); 
string targetPath = System.IO.Path.Combine(@"C:\Users\Developer\Documents\Textfiles", fileOnly); 
System.IO.File.Move(fileName, targetPath); 
+0

如果我不想硬編碼路徑該怎麼辦?不能我做類似.. string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); – JonnyKhanas

2

https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx

的文檔:

destFileName 
Type: System.String 
The name of the destination file. This cannot be a directory or an existing file. 

你必須爲新的文件名添加到目標目錄。你的情況

result = Path.GetFileName(fileName); 

這樣:

您可以獲取文件名

string targetPath = @"C:\Users\Developer\Documents\Textfiles\" + Path.GetFileName(fileName); 
+0

如果我不想硬編碼的路徑?不能我做類似.. string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); – JonnyKhanas

+0

只要路徑是文件名而不是文件夾名即可。 –