2016-12-25 27 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

只要路径是文件名而不是文件夹名即可。 –

相关问题