1

How could I show a progress bar when moving a file?

Currently I've got this:

 private void btnMoveFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (pathFrom != null && pathTo != null)
                {
                    if (txtRename.Text != null)
                    {
                        pathTo = pathTo + "\\" + txtRename.Text;
                    }

                    else
                    {

                        pathTo = pathTo + "\\" + Path.GetFileName(pathFrom);
                    }

                    File.Move(pathFrom, pathTo);
                }

                else
                {
                    MessageBox.Show("Kies eerst een bestand.");
                }
            }

            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i <= 100; i++)
            {
                // Wait 100 milliseconds.
                Thread.Sleep(100);
                // Report progress.
                backgroundWorker1.ReportProgress(i);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            // Set the text.
            this.Text = e.ProgressPercentage.ToString();
        }

But because File.Move(pathFrom, pathTo); is not a loupe I've got no Idea how to do this.

Jamie
  • 10,302
  • 32
  • 103
  • 186
  • call this method asynchronously and while is runing dispplay a loading message – CDrosos Nov 14 '16 at 11:37
  • 1
    If you want to display the progress of the single file-copy, you have to open 2 filesstreams and copy the bytes. This way you can calculate how far you are when copying and you can display a progress. With File.Move you can't – D.J. Nov 14 '16 at 11:40
  • general advice: to make your code portable and survive future releases of the OS, better use the built-in library functions and constants to manipulate your path variables: `Path.Combine` and `Path.DirectorySeparatorChar`. this is too often neglected in publicly available documentation and sample code. – Cee McSharpface Nov 14 '16 at 11:57
  • @dlatikay thanks for the advice. – Jamie Nov 14 '16 at 12:00

1 Answers1

2

Consider using the SHFileOperation API from shell32. A working solution is described in this answer: How to bring up the built-in File Copy dialog? It works for copy as well as for move and delete.

Community
  • 1
  • 1
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77