本文介绍了使用c#将子文件夹中的所有文件移动到另一个文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的源路径是 C:\Music\ 其中有数百个文件夹称为Album-1,Album-2等。



我想做的是在我的源路径中创建一个名为 Consolidated 的文件夹。

然后我想将我的相册中的所有文件移动到文件夹 Consolidated ,以便我将所有音乐文件放在一个文件夹中。 / p>

我该怎么做?

解决方案

p>

  String directoryName =C:\\Consolidated; 
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if(dirInfo.Exists == false)
Directory.CreateDirectory(directoryName);

列表< String> MyMusicFiles =目录
.GetFiles(C:\\\Music,*。*,SearchOption.AllDirectories).ToList();

foreach(MyMusicFiles中的字符串文件)
{
FileInfo mFile = new FileInfo(file);
//删除名称冲突
如果(新的FileInfo(dirInfo +\\+ mFile.Name).Exists == false)
{
mFile.MoveTo (dirInfo +\\+ mFile.Name);
}
}

它将获取所有文件在C: \Music文件夹(包括子文件夹中的文件),并将它们移动到目标文件夹。 SearchOption.AllDirectories 将递归搜索所有子文件夹。


My source path is C:\Music\ in which I have hundreds of folders called Album-1, Album-2 etc.

What I want to do is create a folder called Consolidated in my source path.
And then I want to move all the files inside my albums to the folder Consolidated, so that I get all the music files in one folder.

How can I do this ?

解决方案

Try like this

String directoryName = "C:\\Consolidated";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
    Directory.CreateDirectory(directoryName);

List<String> MyMusicFiles = Directory
                   .GetFiles("C:\\Music", "*.*", SearchOption.AllDirectories).ToList();

foreach (string file in MyMusicFiles)
{
    FileInfo mFile = new FileInfo(file);
    // to remove name collisions
    if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
    {
         mFile.MoveTo(dirInfo + "\\" + mFile.Name);
    }
}

It will get all the files in the "C:\Music" folder (including files in the subfolder) and move them to the destination folder. The SearchOption.AllDirectories will recursively search all the subfolders.

这篇关于使用c#将子文件夹中的所有文件移动到另一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 09:11