Click here to Skip to main content
11,643,493 members (72,650 online)
Click here to Skip to main content

How to copy files in C# with a customizable progress indicator and or progress bar

, 22 May 2009 CPOL 99.1K 8.5K 73
Rate this:
Please Sign up or sign in to vote.
This article shows you how to construct a class to copy files and folder trees with an optional progress indicator.

Copy Files

Introduction

After reading about lots of ways to copy files with a progress indicator in C# and finding them all to be a little... long winded, I decided to write this article to help my fellow coders. It's a simple way to copy files and folders with a customizable progress bar/indicator.

Background

The class uses the Windows Kernal32 CopyFileEx function to do the copying of files. This being said, it does use one pointer, and so needs to be compiled with the /unsafe parameter (or simply tick the 'allow unsafe code' option in the project's properties)

You can create your own way to display the progress of the copy. To do this, simply implement the ICopyFileDiag interface and pass your class to the copy method.

//The interface for the Dialog the CopyFiles class uses.
public interface ICopyFilesDiag
{
    //needed to sync the CopyClass update events with the dialog thread
    System.ComponentModel.ISynchronizeInvoke SynchronizationObject { get; set; }

    //This event should fire when you want to cancel the copy
    event CopyFiles.DEL_cancelCopy EN_cancelCopy;

    //This is how the CopyClass will send your dialog information about
    //the transfer
    void update(Int32 totalFiles, Int32 copiedFiles, Int64 totalBytes, 
                Int64 copiedBytes, String currentFilename);
    void Show();
    void Hide();
}

Using the code

The guts of the code is in the CopyFiles class; however, once this is referenced in your application, it's simply a case of specifying a list of files for a directory to copy and the location to copy it to.

You then choose to do the copy asynchronously or synchronously:

private void But_CopyFiles_Click(object sender, EventArgs e)
{

    //This the list of random files we want 
    //to copy into a single new directory
    List<String> TempFiles = new List<String>();
    TempFiles.Add("C:\\Copy Test Folder\\test.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Bob.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test4\\Bob.Trev.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test4\\test.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test3\\Bob.Trev.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test3\\test.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test3\\B.o.b.Trev..txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test2\\Bob.Trev.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test2\\test.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test1\\test.txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test1\\B.o.b.Trev..txt");
    TempFiles.Add("C:\\Copy Test Folder\\Test1\\Bob.Trev.txt");

    //I would recommend you put at least one large file in this folder
    //to see the progress bar in action.
    CopyFiles.CopyFiles Temp = new CopyFiles.CopyFiles(TempFiles, "C:\\Test");
    
    //Uncomment the next line to copy the file tree.
    //CopyFiles.CopyFiles Temp = 
    // new CopyFiles.CopyFiles("C:\\Copy Test Folder", "C:\\Test");

    //Create the default Copy Files Dialog window from our Copy Files assembly
    //and sync it with our main/current thread
    CopyFiles.DIA_CopyFiles TempDiag = new CopyFiles.DIA_CopyFiles();
    TempDiag.SynchronizationObject = this;

    //Copy the files anysncrinsuly
    Temp.CopyAsync(TempDiag);

    //Uncomment this line to do a synchronous copy.
    ///Temp.Copy();

}

This is an example of how the ICopyFileDiag can be implemented:

public partial class DIA_CopyFiles : Form, ICopyFilesDiag
{
    // Properties
    public System.ComponentModel.ISynchronizeInvoke 
           SynchronizationObject { get; set; }
    // Constructors
    public DIA_CopyFiles()
    {
        InitializeComponent();
    }
    // Methods
    public void update(Int32 totalFiles, Int32 copiedFiles, 
           Int64 totalBytes, Int64 copiedBytes, String currentFilename)
    {
        Prog_TotalFiles.Maximum = totalFiles;
        Prog_TotalFiles.Value = copiedFiles;
        Prog_CurrentFile.Maximum = 100;
        if (totalBytes != 0)
        {
            Prog_CurrentFile.Value = Convert.ToInt32((100f / 
                  (totalBytes / 1024f)) * (copiedBytes / 1024f));
        }
        Lab_TotalFiles.Text = "Total files (" + copiedFiles + 
                  "/" + totalFiles + ")";
        Lab_CurrentFile.Text = currentFilename;
    }
    private void But_Cancel_Click(object sender, EventArgs e)
    {
        RaiseCancel();
    }
    private void DIA_CopyFiles_Closed(object sender, System.EventArgs e)
    {
        RaiseCancel();
    }
    private void RaiseCancel()
    {
        if (EN_cancelCopy != null)
        {
            EN_cancelCopy();
        }
    }
    //Events
    public event CopyFiles.DEL_cancelCopy EN_cancelCopy;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Neil Cadman
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionHow to copy complete directory? Pin
Member 110410572-Sep-14 0:53
memberMember 110410572-Sep-14 0:53 
QuestionCopy and Rename? Pin
ElSEEDY3-Jun-14 4:33
memberElSEEDY3-Jun-14 4:33 
QuestionUser Control copyComplete Event Pin
arbh8915-Nov-12 6:33
memberarbh8915-Nov-12 6:33 
QuestionUpdated Code Pin
jtitley3-Oct-11 18:50
memberjtitley3-Oct-11 18:50 
QuestionRe: Updated Code Pin
scooter_seh7-Apr-12 6:47
memberscooter_seh7-Apr-12 6:47 
AnswerRe: Updated Code Pin
zt08194913-Nov-12 16:40
memberzt08194913-Nov-12 16:40 
GeneralRe: Updated Code Pin
scooter_seh14-Nov-12 1:28
memberscooter_seh14-Nov-12 1:28 
GeneralRe: Updated Code Pin
zt08194914-Nov-12 2:52
memberzt08194914-Nov-12 2:52 
QuestionCopy also empty folders Pin
lozirion10-Feb-11 0:04
memberlozirion10-Feb-11 0:04 
AnswerRe: Copy also empty folders Pin
Gary Noter7-Jul-11 8:20
memberGary Noter7-Jul-11 8:20 
Generalfolder structure Pin
pavelnt26-Nov-10 0:24
memberpavelnt26-Nov-10 0:24 
GeneralMy vote of 5 Pin
B.V.Papadopoulos6-Sep-10 1:06
memberB.V.Papadopoulos6-Sep-10 1:06 
GeneralError Handling Pin
mason.c2-Jun-10 10:45
membermason.c2-Jun-10 10:45 
QuestionCopyfolder for me does not work with large files Pin
Nadeem Rasool15-Apr-10 5:15
memberNadeem Rasool15-Apr-10 5:15 
AnswerRe: Copyfolder for me does not work with large files Pin
Neil Cadman4-May-10 9:49
memberNeil Cadman4-May-10 9:49 
GeneralCool article! Pin
Abhinav S27-Mar-10 21:01
memberAbhinav S27-Mar-10 21:01 
QuestionVery helpful but I would like to copy an entire tree of files and folder. Pin
kakaomocha26-Mar-10 9:05
memberkakaomocha26-Mar-10 9:05 
AnswerRe: Very helpful but I would like to copy an entire tree of files and folder. Pin
Neil Cadman4-May-10 9:52
memberNeil Cadman4-May-10 9:52 
GeneralRe: Very helpful but I would like to copy an entire tree of files and folder. Pin
Neil Cadman4-May-10 10:02
memberNeil Cadman4-May-10 10:02 
GeneralRe: Very helpful but I would like to copy an entire tree of files and folder. Pin
nasermokkary17-May-10 23:40
membernasermokkary17-May-10 23:40 
GeneralRe: Very helpful but I would like to copy an entire tree of files and folder. Pin
Gary Noter7-Jul-11 8:23
memberGary Noter7-Jul-11 8:23 
GeneralVery helpful! Pin
kolluti11-Mar-10 6:20
memberkolluti11-Mar-10 6:20 
GeneralMy vote of 1 Pin
kurtkc9-Mar-10 16:15
memberkurtkc9-Mar-10 16:15 
QuestionTrouble with events EV_copyCanceled and EV_copyComplete Pin
jpangamarca18-Dec-09 6:06
memberjpangamarca18-Dec-09 6:06 
AnswerRe: Trouble with events EV_copyCanceled and EV_copyComplete Pin
Neil Cadman3-Jan-10 8:48
memberNeil Cadman3-Jan-10 8:48 
GeneralRe: Trouble with events EV_copyCanceled and EV_copyComplete Pin
Douglas Kirk20-Feb-10 7:33
memberDouglas Kirk20-Feb-10 7:33 
GeneralRe: Trouble with events EV_copyCanceled and EV_copyComplete Pin
Douglas Kirk20-Feb-10 8:14
memberDouglas Kirk20-Feb-10 8:14 
QuestionCopy Files Pin
direkt12314-Nov-09 21:21
memberdirekt12314-Nov-09 21:21 
AnswerRe: Copy Files Pin
Neil Cadman3-Jan-10 8:35
memberNeil Cadman3-Jan-10 8:35 
QuestionDisplaying progress in synchronous mode Pin
zzzdeejay27-Oct-09 1:24
memberzzzdeejay27-Oct-09 1:24 
AnswerRe: Displaying progress in synchronous mode Pin
Neil Cadman3-Jan-10 8:33
memberNeil Cadman3-Jan-10 8:33 
QuestionCopy folder destination not working?? helpful resource BTW. [modified] Pin
tphengsy@touchsonic.com10-Aug-09 10:26
membertphengsy@touchsonic.com10-Aug-09 10:26 
AnswerRe: Copy folder destination not working?? helpful resource BTW. Pin
Touch Sonic11-Aug-09 8:14
memberTouch Sonic11-Aug-09 8:14 
Generalif do not place in the harddisk, Pin
Burak Akku16-Jun-09 21:39
memberBurak Akku16-Jun-09 21:39 
Generalgood article Pin
Donsw13-Jun-09 7:16
memberDonsw13-Jun-09 7:16 
GeneralRe: good article Pin
Neil Cadman13-Jun-09 22:00
memberNeil Cadman13-Jun-09 22:00 
GeneralRe: good article Pin
Donsw14-Jun-09 4:52
memberDonsw14-Jun-09 4:52 
GeneralNice Article Pin
Four13 Designs29-May-09 17:32
memberFour13 Designs29-May-09 17:32 
AnswerRe: Nice Article Pin
Neil Cadman29-May-09 23:16
memberNeil Cadman29-May-09 23:16 
GeneralRe: Nice Article Pin
mash sundaraman29-Jun-09 11:39
membermash sundaraman29-Jun-09 11:39 
GeneralRe: Nice Article Pin
Neil Cadman29-Jul-09 7:31
memberNeil Cadman29-Jul-09 7:31 
GeneralRe: Nice Article Pin
senlin11019-Dec-09 7:26
membersenlin11019-Dec-09 7:26 
GeneralRe: Nice Article Pin
Neil Cadman3-Jan-10 8:55
memberNeil Cadman3-Jan-10 8:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 22 May 2009
Article Copyright 2009 by Neil Cadman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid