Move all files in subfolders to another folder using c#

随声附和 提交于 2020-01-10 08:52:14

问题


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 ?


回答1:


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.




回答2:


You can use the Directory object to do this, but you might run into problems if you have the same file name in multiple sub directories (e.g. album1\1.mp3, album2\1.mp3) so you might need a little extra logic to tack something unique onto the names (e.g. album1-1.mp4).

    public void CopyDir( string sourceFolder, string destFolder )
    {
        if (!Directory.Exists( destFolder ))
            Directory.CreateDirectory( destFolder );

        // Get Files & Copy
        string[] files = Directory.GetFiles( sourceFolder );
        foreach (string file in files)
        {
            string name = Path.GetFileName( file );

            // ADD Unique File Name Check to Below!!!!
            string dest = Path.Combine( destFolder, name );
            File.Copy( file, dest );
        }

        // Get dirs recursively and copy files
        string[] folders = Directory.GetDirectories( sourceFolder );
        foreach (string folder in folders)
        {
            string name = Path.GetFileName( folder );
            string dest = Path.Combine( destFolder, name );
            CopyDir( folder, dest );
        }
    }



回答3:


Basically, that can be done with Directory.Move:

                try
                {
                    Directory.Move(source, destination);
                }
                catch { }

don't see any reason, why you shouldn't use this function. It's recursive and speed optimized




回答4:


 public void MoveDirectory(string[] source, string target)
    {
        var stack = new Stack<Folders>();
        stack.Push(new Folders(source[0], target));
        while (stack.Count > 0)
        {
            var folders = stack.Pop();
            Directory.CreateDirectory(folders.Target);
            foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
            {
                string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
                if (File.Exists(targetFile)) File.Delete(targetFile); File.Move(file, targetFile);
            }
            foreach (var folder in Directory.GetDirectories(folders.Source))
            {
                stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
            }
        }
        Directory.Delete(source[0], true);
    } 
}


public class Folders { 
    public string Source { 
        get; private set; 
    } 
    public string Target { 
        get; private set; 
    } 
    public Folders(string source, string target) { 
        Source = source; 
        Target = target; 
    } 
}



回答5:


Something like this should get you rolling. You'll have to add error checking and what not (What if there is a subdirectory of source named "Consolidated"? What if Consolidated already exists? Etc.) This is from memory, so pardon any syntax errors, etc.

string source = @"C:\Music";
string[] directories = Directory.GetDirectories(source);
string consolidated = Path.Combine(source, "Consolidated")
Directory.CreateDirectory(consolidated);
foreach(var directory in directories) {
    Directory.Move(directory, consolidated);
}



回答6:


MSDN : msdn.microsoft.com/en-us/library/bb762914.aspx

private void DirectoryCopy(
            string sourceDirName, string destDirName, bool copySubDirs)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            // If the source directory does not exist, throw an exception.
            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourceDirName);
            }

            // If the destination directory does not exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }


            // Get the file contents of the directory to copy.
            FileInfo[] files = dir.GetFiles();

            foreach (FileInfo file in files)
            {
                // Create the path to the new copy of the file.
                string temppath = Path.Combine(destDirName, file.Name);

                // Copy the file.
                file.CopyTo(temppath, false);
            }

            // If copySubDirs is true, copy the subdirectories.
            if (copySubDirs)
            {

                foreach (DirectoryInfo subdir in dirs)
                {
                    // Create the subdirectory.
                    string temppath = Path.Combine(destDirName, subdir.Name);

                    // Copy the subdirectories.
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }



回答7:


You'll probably find this helpful to dedup your mp3's that have a different file name but same title.

source from David @ msdn!

byte[] b = new byte[128];
string sTitle;
string sSinger;
string sAlbum;
string sYear;
string sComm;
FileStream fs = new FileStream(file, FileMode.Open);
fs.Seek(-128, SeekOrigin.End);
fs.Read(b, 0, 128);
bool isSet = false;
String sFlag = System.Text.Encoding.Default.GetString(b, 0, 3);
if (sFlag.CompareTo("TAG") == 0)
{
System.Console.WriteLine("Tag   is   setted! ");
isSet = true;
}
if (isSet)
{
//get   title   of   song; 
sTitle = System.Text.Encoding.Default.GetString(b, 3, 30);
System.Console.WriteLine("Title: " + sTitle);
//get   singer; 
sSinger = System.Text.Encoding.Default.GetString(b, 33, 30);
System.Console.WriteLine("Singer: " + sSinger);
//get   album; 
sAlbum = System.Text.Encoding.Default.GetString(b, 63, 30);
System.Console.WriteLine("Album: " + sAlbum);
//get   Year   of   publish; 
sYear = System.Text.Encoding.Default.GetString(b, 93, 4);
System.Console.WriteLine("Year: " + sYear);
//get   Comment; 
sComm = System.Text.Encoding.Default.GetString(b, 97, 30);
System.Console.WriteLine("Comment: " + sComm);
}
System.Console.WriteLine("Any   key   to   exit! ");
System.Console.Read();



回答8:


        String directoryName = @"D:\NewAll\";
        DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
        if (dirInfo.Exists == false)
            Directory.CreateDirectory(directoryName);

        List<String> AllFiles= Directory
                           .GetFiles(@"D:\SourceDirectory\", "*.*", SearchOption.AllDirectories).ToList();

        foreach (string file in AllFiles)
        {
            FileInfo mFile = new FileInfo(file);

            // to remove name collisions
            if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
            {
                mFile.MoveTo(dirInfo + "\\" + mFile.Name);
            }
            else
            {
                string s = mFile.Name.Substring(0, mFile.Name.LastIndexOf('.'));

                int a = 0;
                while (new FileInfo(dirInfo + "\\" + s + a.ToString() + mFile.Extension).Exists)
                {
                    a++;
                }
                mFile.MoveTo(dirInfo + "\\" + s + a.ToString() + mFile.Extension);
            }
        }



回答9:


You loop through them and then simply run Move, the Directory class have functionality for listing contents too iirc.




回答10:


You might be interested in trying Powershell and/or Robocopy to do this task. It'll be a lot more concise than creating a C# application for the task. Powershell is also a great tool for your development tool-belt.

I believe Powershell and Robocopy are both installed by default on Windows Vista and 7.

This might be a good place to start: http://technet.microsoft.com/en-us/library/ee332545.aspx




回答11:


class Program
{
    static void Main(string[] args)
    {
        movedirfiles(@"E:\f1", @"E:\f2");
    }
    static void movedirfiles(string sourdir,string destdir)
    {
        string[] dirlist = Directory.GetDirectories(sourdir);

        moveallfiles(sourdir, destdir);
        if (dirlist!=null && dirlist.Count()>0)
        {
            foreach(string dir in dirlist)
            {
                string dirName = destdir+"\\"+ new DirectoryInfo(dir).Name;
                Directory.CreateDirectory(dirName);
                moveallfiles(dir,dirName);
            }
        }

    }
    static void moveallfiles(string sourdir,string destdir)
    {
        string[] filelist = Directory.GetFiles(sourdir);
        if (filelist != null && filelist.Count() > 0)
        {
            foreach (string file in filelist)
            {
                File.Copy(file, string.Concat(destdir, "\\"+Path.GetFileName(file)));
            }
        }
    }

}


来源:https://stackoverflow.com/questions/3911595/move-all-files-in-subfolders-to-another-folder-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!