none
How to copy new added folder in Source folder to Target folder by clicking a button? RRS feed

  • Question

  • Hello everyone, 

    I am using Visual C# and create user interface. There have only one button in interface.

    There have 2 folders with name 'Source' and 'Target', in 'Source' folder contains '2019', '2018', '2017' folders. Once a day, there is 1 folder's name start with '201904" with 10 file's name start with "text" will be downloaded and move to "C:/Users/Source/2019/". 

    According to codes that I have for now:

    In day 1, I have been click a button and then a folder "20190401"  in "C:/Users/Source/2019/" copied to "C:/Users/Target/".

    But in day 2, the new downloaded folder "20190402" in '"C:/Users/Source/2019/" wouldn't copy to "C:/Users/Target/" after I click a button for 2nd time, because it cannot overwrite the existed "20190401" folder in "C:/Users/Target/".

    The result that I expected, "C:/Users/Target/" will collects "201904**"folder in daily by clicking button once a day. Furthermore, only [3] files in folder "201904**" name start with "text" will be copy to "C:/Users/Target/". Do you guys have any idea to solve this problem? 

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

    Best regards,

    Pugita






    • Edited by Pugita Monday, April 15, 2019 9:03 AM
    Monday, April 15, 2019 7:31 AM

Answers

  • Hi

    According to your description, you could try the following code.

     string FROM_DIR = @"D:\dir\Source";
            string TO_DIR = @"D:\dir\Target";
            public Form1()
            {
                InitializeComponent();
            }
            public int num { get; set; }
            
            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);
                    }
                }
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
    
                DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
                DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
                string directname = "2019040";
                string filename = "text";
                int count = 0;
                foreach (DirectoryInfo newfile in fiDiskfiles)
                {
                    try
                    {
                        if (newfile.Name == "2019")
                        {
                            foreach (DirectoryInfo direc in newfile.GetDirectories())
                                foreach (FileInfo file in direc.GetFiles())
                                {
                                  
                                    if (direc.Name == directname + num.ToString())
                                    {
                                      
                                        if (file.Name.StartsWith(filename))
                                        {
                                            count++;  
                                        }
                                        if (count==3)
                                        {
                                            DirectoryCopy(direc.FullName, Path.Combine(TO_DIR, direc.Name), true);
                                            count = 0;
                                            DirectoryInfo info = new DirectoryInfo(Path.Combine(TO_DIR, direc.Name));
                                            foreach (FileInfo fileInfo in info.GetFiles())
                                            {
                                             if(!fileInfo.Name.StartsWith(filename))
                                                {
                                                    File.Delete(fileInfo.FullName);
                                                }
                                            }
                                            foreach (FileInfo fileInfo in info.GetFiles())
                                            {
                                                count++;
                                                if(count>3)
                                                {
                                                    File.Delete(fileInfo.FullName);
                                                }
                                            }
                                           
                                        }
    
                                    }
                                }
    
                        }
    
                    }
    
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                MessageBox.Show("success");
            }
            
            private void Form1_Load(object sender, EventArgs e)
            {
                string datetime = "2019/04/16";
                int d1 = Convert.ToDateTime(datetime).Day;
                int d2 = DateTime.Now.Day;
                num = d2 - d1 + 1;
            }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, April 16, 2019 6:23 AM
    Moderator

All replies

  • Hi

    Thank you for posting here.

    Based on your description, you want to collect "201904**"folder in daily by clicking button once a day and copy "201904**" folders with 3 text files inside it to Target folder.

    I think these two functions will conflict, so I suggest that you can write these two functions separately.

    You could try the following code, then button 1 event is used for the latter and button event 2 is for the former.

       public partial class Form1 : Form
        {
            string FROM_DIR = @"D:\dir\Source";
            string TO_DIR = @"D:\dir\Target";
            string to_dir= @"D:\dir\newtarget";
    
            public Form1()
            {
                InitializeComponent();
            }
            public int num { get; set; }
            private void button1_Click(object sender, EventArgs e)
            {
                DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
                DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
                string directname = "2019040";
                string filename = "text";
           
                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.StartsWith(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);
                    }
                }
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
                DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
                string directname = "2019040";
                foreach (DirectoryInfo newfile in fiDiskfiles)
                {
                    try
                    {
                        if (newfile.Name == "2019")
                        {
                            foreach (DirectoryInfo direc in newfile.GetDirectories())
    
                                if (direc.Name==directname+num.ToString())
                                {
                                        DirectoryCopy(direc.FullName, Path.Combine(TO_DIR, direc.Name), true);
                                }
    
                        }
    
                    }
    
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                MessageBox.Show("success");
            }
            
            private void Form1_Load(object sender, EventArgs e)
            {
                string datetime = "2019/04/15";
                int d1 = Convert.ToDateTime(datetime).Day;
                int d2 = DateTime.Now.Day;
                num = d2 - d1 + 1;
            }
        }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, April 15, 2019 9:21 AM
    Moderator
  • Hello Jack, 

    Thank you so much for your feedback Mr. Jack. I'm so sorry Sir, maybe because of my bad grammar my question was be not very clear. But I so appreciated your concern to my questions Sir. The expected result that I was looking for is like these 2 GIF. Both of these GIF were my edited video. I hope it will help you to understand my question.

    First GIF shows there have one folder "20190401" contains various of files and have more "text" files inside it. This folder was downloaded and move to "Source" folder. After I click a button, folder "20190401" will copy to "Target" folder with 3 files name start with "text". 

    The "Source" folder will received folder "201904++" anytime. "201904++" folder contains various of files same as "20190401" folder.

    Second GIF shows there have one folder "20190402" contains various of files. This folder was downloaded and move to "Source" folder too. after I click a button, folder "20190402" will copy to "Target" folder with 3 files name start with "text" and "20190401" not changed. 

    I hope you can help me, thank you.

    Best regards, 

    Pugita



    • Edited by Pugita Monday, April 15, 2019 2:22 PM
    Monday, April 15, 2019 2:14 PM
  • Hi

    Thanks for the feedback.

    For your question, I want to confirm a question with you.

    In the first video, your 20190401 contains multiple text files, but your final result only copies 3 text files. I want to ask if I get three text files randomly or get the first three text files.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, April 16, 2019 1:45 AM
    Moderator
  • Hello Mr. Jack,

    Thank you for your response. For your question, the answer is "get the first three text files".

    20190401 having multiples of files and definitely will have more than or equal 3 files name start with "text". The upcoming folder also will have multiples of files definitely >= 3 files name start with "text".

    For example, 20190401 have [10] files = {"text01.txt", "text02.txt", "text03.txt", "text04.txt", "text05.txt", "image1.png", "image2.png", "image3.png", "image4.png", "image5.png"}  

    After click a button, folder 20190401 containing files "text01.txt", "text02.txt" and "text03.txt" copied to 'Target' folder.

    Later, 20190402 is downloaded and move to 'Source' folder. 20190402 have [9] files = {text02.txt", "text03.txt", "text04.txt", "text05.txt, "image03.png", "image04.png", "image05.png", "image06.png", "image07.png"}

    After click a button again, folder 20190402 with containing files "text02.txt", "text03.txt, and "text04.txt" copied to 'Target'. At this time, folder 20190401 will remains and not changed. So 'Target' folder have 2 folder now.

    Later, new folder will downloaded and it's name is 20190403. 20190403 have [5] files = {"text01.txt", "text02.txt", "text03.txt", "image01.png", "image02.png"}

    After click a button again, 20190403 containing files "text01.txt", "text02.txt" and "text03.txt" copied to 'Target' folder. 20190401 and 20190402 in 'target' folder are remains and not changed. Now 'Target' have 3 folder "201904++" .

    Conclusion: My expected result is after I click a button, the 'Target' folder will received folder '201904++' with 3 files only and these files's name start with "text" from 'Source'.  

    If my explaination is not clear, just ask me. I will give more example. By the way, thanks a lot for your concern Sir.

    Best regard,

    Pugita 






    • Edited by Pugita Tuesday, April 16, 2019 3:31 AM
    Tuesday, April 16, 2019 3:13 AM
  • Hi

    According to your description, you could try the following code.

     string FROM_DIR = @"D:\dir\Source";
            string TO_DIR = @"D:\dir\Target";
            public Form1()
            {
                InitializeComponent();
            }
            public int num { get; set; }
            
            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);
                    }
                }
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
    
                DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
                DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
                string directname = "2019040";
                string filename = "text";
                int count = 0;
                foreach (DirectoryInfo newfile in fiDiskfiles)
                {
                    try
                    {
                        if (newfile.Name == "2019")
                        {
                            foreach (DirectoryInfo direc in newfile.GetDirectories())
                                foreach (FileInfo file in direc.GetFiles())
                                {
                                  
                                    if (direc.Name == directname + num.ToString())
                                    {
                                      
                                        if (file.Name.StartsWith(filename))
                                        {
                                            count++;  
                                        }
                                        if (count==3)
                                        {
                                            DirectoryCopy(direc.FullName, Path.Combine(TO_DIR, direc.Name), true);
                                            count = 0;
                                            DirectoryInfo info = new DirectoryInfo(Path.Combine(TO_DIR, direc.Name));
                                            foreach (FileInfo fileInfo in info.GetFiles())
                                            {
                                             if(!fileInfo.Name.StartsWith(filename))
                                                {
                                                    File.Delete(fileInfo.FullName);
                                                }
                                            }
                                            foreach (FileInfo fileInfo in info.GetFiles())
                                            {
                                                count++;
                                                if(count>3)
                                                {
                                                    File.Delete(fileInfo.FullName);
                                                }
                                            }
                                           
                                        }
    
                                    }
                                }
    
                        }
    
                    }
    
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                MessageBox.Show("success");
            }
            
            private void Form1_Load(object sender, EventArgs e)
            {
                string datetime = "2019/04/16";
                int d1 = Convert.ToDateTime(datetime).Day;
                int d2 = DateTime.Now.Day;
                num = d2 - d1 + 1;
            }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, April 16, 2019 6:23 AM
    Moderator
  • Hello Jack,

    Your codes is works! Thank you so much for helping me Mr. Jack. I really appreciate your help. 

    Sincerely yours,

    Pugita 


    • Edited by Pugita Tuesday, April 16, 2019 8:13 AM
    Tuesday, April 16, 2019 8:13 AM