Есть ли какой-нибудь способ скопировать последние файлы и папки из исходного кода (отсортировать новые файлы и папки create) с помощью c #?

#c#

#c#

Вопрос:

Пример кода

Я хочу сохранить файлы, нажав флажок и кнопку, но проблема в том, что я хочу сохранить только последние файлы и папки. Есть ли какой-нибудь способ отсортировать дату назначения перед копированием папки?

Вот весь код:

 namespace NewFunctionTesting
{
    public partial class Form1 : Form
    {
        //variable
        int count = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            count  ; //for button
            if (checkBox1.Checked == true amp;amp; count == 1) //first testing
            {
                //copy latest 1
                string ProductionImage = @"C:UsersIM10DocumentsImage";
                string NewProductionImage = @"C:UsersIM10DocumentsNewImage";
                Copy(ProductionImage, NewProductionImage);

                string ProductionIImageValue = @"C:UsersIM10DocumentsValue";
                string NewProductionIImageValue = @"C:UsersIM10DocumentsNewValue";
                Copy(ProductionIImageValue, NewProductionIImageValue);
            }
            else if (checkBox1.Checked == true amp;amp; count == 2) //second testing
            {
                //copy latest 2
                string ProductionImage = @"C:UsersIM10DocumentsImage";
                string NewProductionImage = @"C:UsersIM10DocumentsNewImage";
                Copy(ProductionImage, NewProductionImage);

                string ProductionIImageValue = @"C:UsersIM10DocumentsValue";
                string NewProductionIImageValue = @"C:UsersIM10DocumentsNewValue";
                Copy(ProductionIImageValue, NewProductionIImageValue);
            }
            else if (checkBox1.Checked == true amp;amp; count >= 3) //third testing
            {
                //uncheck the checkbox
                checkBox1.Checked = false;
                count = 0;

                //copy latest 3
                string ProductionImage = @"C:UsersIM10DocumentsImage";
                string NewProductionImage = @"C:UsersIM10DocumentsNewImage";
                Copy(ProductionImage, NewProductionImage);

                string ProductionIImageValue = @"C:UsersIM10DocumentsValue";
                string NewProductionIImageValue = @"C:UsersIM10DocumentsNewValue";
                Copy(ProductionIImageValue, NewProductionIImageValue);
            }
            else if (checkBox1.Checked == false) 
            {
                count = 0;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //empty
        }

        public static void Copy(string sourceDirectory, string targetDirectory)
        {
            var diSource = new DirectoryInfo(sourceDirectory);
            var diTarget = new DirectoryInfo(targetDirectory);

            CopyAll(diSource, diTarget);
        }

        public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            Directory.CreateDirectory(target.FullName);

            // Copy each file into the new directory
            foreach (FileInfo fi in source.GetFiles())
            {
                fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
            }

            // Copy each subdirectory using recursion (i need to sort the folder date)
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories().OrderBy(fi => fi.LastWriteTime).ToList())
            {
                    DirectoryInfo nextTargetSubDir =
                        target.CreateSubdirectory(diSourceSubDir.Name);
                    CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }

        public static FileInfo GetNewestFile(DirectoryInfo directory)
        {
            return directory.GetFiles()
                .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
                .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
                .FirstOrDefault();
        }

    }
}
 

Комментарии:

1. Какая будет разница, если вы отсортируете файлы перед копированием? Эффект будет таким же в конце или?

2. Этот код скопирует все файлы и папки в новый каталог, но я хочу что-то, что копирует последнюю версию (последнее создание). Поэтому я думаю, что мне может понадобиться функция сортировки, чтобы скопировать только определенную папку. Например, в каталоге создано много папок, и я хочу скопировать последнюю папку, содержащую файлы (последнее создание), в новое местоположение.

3. Directory.GetCreationTime(String)