Как скопировать конкретную папку в новую папку, нажав кнопку - PullRequest
0 голосов
/ 13 апреля 2019

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

Здесь мой код на данный момент, после нажатия кнопки папка не будет копироваться. Я думаю, что есть некоторые проблемы с этими кодами, и я до сих пор не нашел его до. Надеюсь, вы, ребята, можете мне помочь, спасибо.

*namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
  string FROM_DIR = "C:/Users/Desktop/Source/";
  string TO_DIR = "C:/Users/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;
                            MessageBox.Show("success");
                        }
                    }

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


    }

    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 ".txt файлы в папке (Source) в (целевую папку).

1 Ответ

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

Вы не сказали, какие 3 текстовых файла вы хотите скопировать, поэтому приведенный ниже код копирует все текстовые файлы, пожалуйста, объясните, как вы выбираете файлы, и я отредактирую код.

        const string Source = @"C:\Users\Desktop\Source\";
        const string Target = @"C:\Users\Desktop\Target\";
        const string StartsWith = "201904";
        const string FileType = "txt";
        public static void Copy()
        {
            if (!Directory.Exists(Source)) //Check if the source directory exists
                throw new Exception("Source directory is missing!");

            Directory.CreateDirectory(Target); //If the target directory doesn't exists it will create one
            var Directories = Directory.GetDirectories(Source, $"{StartsWith}*"); //Get directories which match the search pattern
            for (int i = 0; i < Directories.Length; i++)
            {
                DirectoryInfo directory = new DirectoryInfo(Directories[i]);
                Directory.CreateDirectory($"{Target}{directory.Name}"); //Create the directory in the target folder

                var Files = Directory.GetFiles($"{Source}{directory.Name}", $"*.{FileType}"); //Get files
                for (int j = 0; j < Files.Length; j++)
                {
                    FileInfo file = new FileInfo(Files[j]);
                    File.Copy($"{Source}{directory.Name}" + @"\" + file.Name, $"{Target}{directory.Name}" + @"\" + file.Name); //Copy the file to the target folder
                }
            }
        }

ЭтоКод выбирает все каталоги, которые начинаются с «201904» и все текстовые файлы внутри них, и копирует их в целевую папку.

РЕДАКТИРОВАТЬ: исправлена ​​ошибка в коде

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...