【问题标题】:How do I move a file to a directory and not replacing a file?如何将文件移动到目录而不替换文件?
【发布时间】:2017-05-10 08:54:10
【问题描述】:

我正在尝试将文件从桌面移动到名为“Textfiles”的目录,但每次尝试时都会出现此错误。

补充信息:目标文件“C:\Users\Developer\Documents\Textfiles”是目录,不是文件。

现在我知道使用

File.Copy(fileName, targetPath);

会出错,这就是我现在使用的,它需要两个参数,第一个是你要复制的文件,第二个是它要替换的文件?如果我在第二个参数上错了,请纠正我。

无论如何,我也尝试了System.IO.Directory.Move(fileName, destFile);,但这几乎给了我同样的错误。

这两个参数很简单,就是由路径组成的两个字符串。

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

将 fileName 传输到 targetPath 的正确方法是什么?

【问题讨论】:

    标签: c# .net file io directory


    【解决方案1】:

    您需要指定目标文件名。

    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);
    

    【讨论】:

    • 如果我不想硬编码路径怎么办?我不能做类似.. string path =Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    【解决方案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);
    

    【讨论】:

    • 如果我不想硬编码路径怎么办?我不能做类似.. string path =Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    • 可以,只要路径是文件名而不是文件夹名。
    猜你喜欢
    • 2020-02-01
    • 2016-05-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多