将文件从一个文件夹移动到另一个文件夹 C#

38

各位,我正在尝试将所有以“_DONE”结尾的文件移动到另一个文件夹中。

我尝试过:

//take all files of main folder to folder model_RCCMrecTransfered 
string rootFolderPath = @"F:/model_RCCMREC/";
string destinationPath = @"F:/model_RCCMrecTransfered/";
string filesToDelete = @"*_DONE.wav";   // Only delete WAV files ending by "_DONE" in their filenames
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);
foreach (string file in fileList)
{
    string fileToMove = rootFolderPath + file;
    string moveTo = destinationPath + file;
    //moving file
    File.Move(fileToMove, moveTo);

但是在执行这些代码时,我收到一个错误,上面说:

给定的路径格式不受支持。

我哪里做错了吗?

4个回答

34

您的斜杠方向是错误的。在 Windows 上,您应该使用反斜杠。例如:

string rootFolderPath = @"F:\model_RCCMREC\";
string destinationPath = @"F:\model_RCCMrecTransfered\";

你的意思是,“在Windows上,你不应该使用正斜杠”吗? - Zed
Path.Combine可以帮助处理平台相关的路径分隔符,但是需要注意一些细节;请参见此处:https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine - ryanwebjackson

29

我是这样做的:

if (Directory.Exists(directoryPath))
{
    foreach (var file in new DirectoryInfo(directoryPath).GetFiles())
    {
        file.MoveTo($@"{newDirectoryPath}\{file.Name}");
    }
}

文件是FileInfo类的一种类型。它已经有一个名为MoveTo()的方法,该方法接受目标路径作为参数。


1
我刚在我正在工作的项目中实现了这个。感谢您提供的解决方案!:D - htmlbran86
1
这似乎是我能够让其正常工作的唯一解决方案。谢谢!!! - Daniel L. VanDenBosch

10
System.IO.Directory.GetFiles()返回的文件名数组包括它们的完整路径。(请参阅http://msdn.microsoft.com/en-us/library/07wt70x2.aspx)这意味着将源目录和目标目录附加到file值上不会得到您期望的结果。你最终会得到像F:\model_RCCMREC\F:\model_RCCMREC\something_DONE.wav这样的值。fileToMove。如果在File.Move()行上设置断点,可以查看传递的值,这有助于调试此类情况。
简而言之,您需要确定从rootFolderPath到每个文件的相对路径,以确定正确的目标路径。查看System.IO.Path类(http://msdn.microsoft.com/en-us/library/system.io.path.aspx)中将有帮助的方法。(特别是,您应该考虑使用Path.Combine()而不是+来构建路径。)

1
请尝试以下函数。它可以正常工作。
函数:
public static void DirectoryCopy(string strSource, string Copy_dest)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(strSource);

        DirectoryInfo[] directories = dirInfo.GetDirectories();

        FileInfo[] files = dirInfo.GetFiles();

        foreach (DirectoryInfo tempdir in directories)
        {
            Console.WriteLine(strSource + "/" +tempdir);

            Directory.CreateDirectory(Copy_dest + "/" + tempdir.Name);// creating the Directory   

            var ext = System.IO.Path.GetExtension(tempdir.Name);

            if (System.IO.Path.HasExtension(ext))
            {
                foreach (FileInfo tempfile in files)
                {
                    tempfile.CopyTo(Path.Combine(strSource + "/" + tempfile.Name, Copy_dest + "/" + tempfile.Name));

                }
            }
            DirectoryCopy(strSource + "/" + tempdir.Name, Copy_dest + "/" + tempdir.Name);

        }

        FileInfo[] files1 = dirInfo.GetFiles();

        foreach (FileInfo tempfile in files1)
        {
            tempfile.CopyTo(Path.Combine(Copy_dest, tempfile.Name));

        }
}

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