[英]How do I move a file to a directory and not replacing a file?
我正在尝试将文件从桌面移动到名为“ Textfiles”的目录,但是每次尝试这样做都会出现此错误。
附加信息:目标文件“ 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的正确方法是什么?
参见https://msdn.microsoft.com/zh-cn/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);
您需要指定目标文件名。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.