Header add


In this article we will learn how to copy file from Source to destination with Progress Bar in WPF.
Let's take an example of WPF and discuss how to copy the file with Progress Bar.

Step-1
Step-2
Open the Mainwindow.xaml and add the below design.
We take File Dialog for Source and textbox for Destination and Progress Bar to show the Percentage.Copy button is used for copy the file from source to destination.
The MainWindow.xaml code as like below:
    <Window x:Class="WPF_CopyFileWithProgressBar.MainWindow"  
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
         xmlns:local="clr-namespace:WPF_CopyFileWithProgressBar"  
         mc:Ignorable="d"  
         Title="MainWindow" Height="450" Width="800">  
       <Grid Margin="0,0,-322,-111">  
         <Label Content="Source" HorizontalAlignment="Left" Margin="56,56,0,0" VerticalAlignment="Top" FontSize="20"/>  
         <Label Content="Destination" HorizontalAlignment="Left" Margin="56,125,0,0" VerticalAlignment="Top" FontSize="20"/>  
         <TextBox HorizontalAlignment="Left" Height="31" Margin="207,62,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="328" Name="txtSource"/>  
         <TextBox HorizontalAlignment="Left" Height="31" Margin="207,132,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="448" Name="txtDestination"/>  
         <ProgressBar HorizontalAlignment="Left" Height="23" Margin="207,179,0,0" VerticalAlignment="Top" Width="426" Name="progressBar"/>  
         <Button Content="Copy" HorizontalAlignment="Left" Margin="207,224,0,0" VerticalAlignment="Top" Width="89" Height="32" Click="Button_Click"/>  
         <Label Content="0%" HorizontalAlignment="Left" Margin="638,176,0,0" VerticalAlignment="Top" Name="lblPercent"/>  
         <Button Content="Browse" HorizontalAlignment="Left" Margin="558,62,0,0" VerticalAlignment="Top" Width="97" Height="31" Click="Button_Click_1"/>  
       </Grid>  
     </Window>  
Step-3
Create button click event on Browse button and add the OpenFileDialog to hold the file information in source text box and also to hold the file name as well.
    private void Button_Click_1(object sender, RoutedEventArgs e)  
         {  
           OpenFileDialog fileDialog = new OpenFileDialog();  
           if (fileDialog.ShowDialog() == true)  
           {  
             foreach (string filename in fileDialog.FileNames)  
             {  
               txtSource.Text = filename; // lbFiles.Items.Add(Path.GetFileName(filename));  
               DestFileName = System.IO.Path.GetFileName(filename);  
             }  
           }  
         }  
Step-4
Create a class named as FileCopy.cs with method named as Copyfile. This method manage copy the file form source to destination with progress bar percentage.
     namespace WPF_CopyFileWithProgressBar  
     {  
      public static class FileCopy  
       {  
         public static void Copyfile(this FileInfo file, FileInfo destination, Action<int> progressCallback)  
         {  
           const int bufferSize = 1024 * 1024;  
           byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];  
           bool swap = false;  
           int progress = 0, reportedProgress = 0, read = 0;  
           long len = file.Length;  
           float flen = len;  
           Task writer = null;  
           using (var source = file.OpenRead())  
           using (var dest = destination.OpenWrite())  
           {  
             dest.SetLength(source.Length);  
             for (long size = 0; size < len; size += read)  
             {  
               if ((progress = ((int)((size / flen) * 100))) != reportedProgress)  
                 progressCallback(reportedProgress = progress);  
               read = source.Read(swap ? buffer : buffer2, 0, bufferSize);  
               writer?.Wait();  
               writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);  
               swap = !swap;  
             }  
             writer?.Wait();  
           }  
         }  
       }  
     }  
Step-5 
Create click event of button name Copy and add the code
    private void Button_Click(object sender, RoutedEventArgs e)  
         {  
           var _source = new FileInfo(txtSource.Text);  
           var _destination = new FileInfo(txtDestination.Text+ "/"+DestFileName);  
           //Check if the file exists, we will delete it  
           if (_destination.Exists)  
             _destination.Delete();  
           //Create a tast to run copy file  
           Task.Run(() =>  
           {  
             _source.Copyfile(_destination, x => progressBar.Dispatcher.BeginInvoke(new Action(() => { progressBar.Value = x; lblPercent.Content = x.ToString() + "%"; })));  
           }).GetAwaiter().OnCompleted(() => progressBar.Dispatcher.BeginInvoke(new Action(() => { progressBar.Value = 100; lblPercent.Content = "100%"; MessageBox.Show("You have successfully copied the file !", "Message", MessageBoxButton.OK, MessageBoxImage.Information); })));  
         }  
Step-6
Run the application and see the output like below:


</> The Source Code is available in Github.com/CoreProgramm/


Summary
     In this tutorial we discussed how to Copy File with Progress Bar in WPF. If have any question related to this topic then give your feedback.

Post a Comment

Previous Post Next Post