Копировать определенную папку только с 3 файлами в новую папку - PullRequest
0 голосов
/ 13 апреля 2019

Один вопрос о кодировании (Visual Studio C # WindowsformApplication) Там есть две папки: (Source and Target) и я строю 1 кнопку "Copy". В папке "Source" есть случайные папки, такие как "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Каждая из этих папок имеет [10] .txt файлов. Что такое кодирование, если я хочу скопировать все папки "201904**" с файлами [3] .txt внутри него в папку "Target"? Вот мой код на данный момент.

Код

  ** 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);
            }
        }
    }**

Я ожидаю после нажатия кнопки, вывод автоматически копирует все папки. Имя Начинается с "201904**" с текстовыми файлами [3] внутри из папки "Source" в папку "target".

1 Ответ

0 голосов
/ 13 апреля 2019

Я считаю, что вы можете искать в каталоге по именам напрямую, используя linq, и можете копировать в него подпапки / файлы, как показано ниже. Это даст вам возможность фильтровать папки / файлы / пропускать / принимать n папок / файлов

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);
}

Протестировал также с подпапками и файлами внутри исходной папки. Надеюсь, это поможет.

...