使用C#将文件移动到目录下

3
string str = "C:\\efe.txt";
string dir = "D:\\";

我想移动或复制"D:\"目录下的"efe.txt"文件。我该怎么做呢?
谢谢您的建议...
3个回答

7

正如其他人提到的,您需要使用File.Move,但是考虑到您的输入,您还需要使用Path.CombinePath.GetFileName,如下所示

string str = "C:\\efe.txt";
string dir = "D:\\";
File.Move(str, Path.Combine(dir, Path.GetFileName(str)));

5

来自MSDN:如何:复制、删除和移动文件和文件夹(C#编程指南):

// Simple synchronous file move operations with no user interface. 
public class SimpleFileMove
{
    static void Main()
    {
        string sourceFile = @"C:\Users\Public\public\test.txt";
        string destinationFile = @"C:\Users\Public\private\test.txt";

        // To move a file or folder to a new location:
        System.IO.File.Move(sourceFile, destinationFile);

        // To move an entire directory. To programmatically modify or combine 
        // path strings, use the System.IO.Path class.
        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
    }
}

4

尝试使用File.Move函数。

using System.IO;
...
string src = "C:\\efe.txt";
string dest = "D:\\efe.txt";
File.Move(src, dest);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接