简体   繁体   中英

Copy specific Folder with 3 Files only to New Folder

One Question about coding (Visual Studio C# WindowsformApplication) There have Two folder: (Source and Target) and I build 1 button "Copy" . In "Source" folder have random folders such as "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401" . Every these folders have [10] .txt files. What is the coding if I only want to copy all "201904**" folders with [3] .txt files inside it to "Target" folder? Here is my code for now.

Code

  ** private void button1_Click

    {
      string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
      string TO_DIR = "C:/Users/5004117928/Desktop/Target/";         
      DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
      DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
      string directname = "201904";
      string filename = ".txt";

        foreach (DirectoryInfo newfile in fiDiskfiles)
        {
            try
            {
                if (newfile.Name == "2019")
                {
                    foreach (DirectoryInfo direc in newfile.GetDirectories())
                        if (direc.Name.StartsWith(directname))
                        {
                            int count = 0;
                            foreach (FileInfo file in direc.GetFiles())
                            {
                                if (file.Name.EndsWith(filename))
                                {
                                    count++;
                                }
                            }
                            if (count == 3)
                            {
                                DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
                                count = 0;
                            }
                        }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        MessageBox.Show("success");
    }
    private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }
        DirectoryInfo[] dirs = dir.GetDirectories();
        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }
        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }
        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }**

I expect after I click a button, output is automatically copy all folders Name Start With "201904**" with [3] text files inside from "Source" folder to "target" folder.

I reckon you can search the directory with names directly using linq and can copy the sub folders/files inside it like below. It will give you the flexibility of filtering folders/files/skipping/taking n folders/files

string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/"; 

string searchText = "201904";
string extension = "txt";

IEnumerable<string> dirs =  Directory.EnumerateDirectories(FROM_DIR, "*", SearchOption.AllDirectories)
          .Where(dirPath=>Path.GetFileName(dirPath.TrimEnd(Path.DirectorySeparatorChar)).StartsWith(searchText));

foreach (string dir in dirs)
{
      string destDirPath = dir.Replace(FROM_DIR, TO_DIR);

      if (!Directory.Exists(destDirPath))
           Directory.CreateDirectory(destDirPath);

       //Copy all the files & Replaces any files with the same name
       foreach (string newPath in Directory.EnumerateFiles(dir, string.format("*.{0}",extension), 
           SearchOption.AllDirectories))// Here you can skip/take n files if u need
              File.Copy(newPath, newPath.Replace(FROM_DIR, TO_DIR), true);
}

Have tested with sub folders and files inside source folder as well. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM