Dailycode.info

Short solution for short problems

Directory copy(program attached to this post can be downloaded)

On request I created a small program that can copy one directory(including subdirectoies and files) to another directory. Nothing special, windows can do that. But The requirement was that only files created after a certain date needed to be copied.
It can be usefull for backup strategies or archiving.
Here a screenshot of this program.
 

 
Feel free to ask for the source code. Here a little snippet (This is a recursive function that loops over all files and directories. This functino is called in a seperate thread, so its not blocking the main thread and it can be stopped at all times.):
 
private void CopyDirStructure(string path, string searchdir)
{
    try
    {
        bool noOutput=false;
        if (GetOutputSize() > 2147400000)
        {
            SetOutput("\n!!!rest concatinated, to many files...!!!\n");
            noOutput=true;
        }
 
        DirectoryInfo dir = new DirectoryInfo(path);
        DirectoryInfo[] subDirs = dir.GetDirectories();
        FileInfo[] files = dir.GetFiles();
        
        int dept = 0;
 
        if (dir.FullName != searchdir)
        {
            if (files.Length > 0)
            {
                CreateDirAtDest(dir, noOutput);
            }
        }
        
        
        
            
        decimal dSize = 0;
        foreach (FileInfo fi in files)
        {
            bool bCopy = true;
            
            if (UseModifyDate())
            {
                if (fi.LastWriteTime < GetModifyDate())
                {
                    bCopy = false;
                }
            }
            if (bCopy)
            {
                if (CopyFileToDest(fi.FullName.ToString(), noOutput))
                {
                    dSize += Math.Round((decimal)fi.Length / 1024, 0, MidpointRounding.ToEven);
                    totalFileCount++;
                }
            }
        }
 
        
        
        totalSize += dSize;
       
        if (subDirs != null)
        {
            dept++;
            foreach (DirectoryInfo sd in subDirs)
            {
                CopyDirStructure(path + @"\\" + sd.Name, searchdir);
                totalDirCount++;
            }
        }
 
        SetDirCount(totalDirCount);
        SetFileCount(totalFileCount);
        SetSize(totalSize);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
}
The controls are updated after each file, because the copy is running in a seperate thread,
be sure that you invoke the controls before trying to update them:
 
public void SetFileCount(int c)
{
    if (this.lbltotal.InvokeRequired)
    {
        this.lbltotal.BeginInvoke(
            new MethodInvoker(
            delegate() { SetFileCount(c); }));
    }
    else
    {
        this.lbltotal.Text = c.ToString() + " files";
    }
}

Download the program here:

CopyFiles.zip (62.17 kb)