Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6019125
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T03:22:31+00:00 2026-05-23T03:22:31+00:00

I’m coding a class to move and copy files. I’m raising events when the

  • 0

I’m coding a class to move and copy files. I’m raising events when the current file progress and the total progress changes. When I test the code on my XP machine, it works fine, but when I run it on my Windows 7 64-Bit machine, the current progress doesn’t update the UI correctly. The current progress ProgressBar only gets half way then starts on the next file which does the same. The total progress ProgressBar updates fine. Any ideas why this is happening?

EDIT: The Windows 7 machine is running a quad-core and the XP is running a dual-core. Not sure if that might be what’s making a difference. I’m only a hobbyist so excuse my ignorance 🙂

EDIT: Code added (Background)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;

namespace nGenSolutions.IO
{
public class FileTransporter
{
    #region Delegates

    public delegate void CurrentFileChangedEventHandler(string fileName);

    public delegate void CurrentProgressChangedEventHandler(int      percentComplete);

    public delegate void CurrentWriteSpeedUpdatedEventHandler(long bytesPerSecond);

    public delegate void TotalProgressChangedEventHandler(int percentComplete);

    public delegate void TransportCompleteEventHandler(FileTransportResult result);

    #endregion

    private readonly List<string> _destinationFiles = new List<string>();
    private readonly List<string> _sourceFiles = new List<string>();

    private long _bytesCopiedSinceInterval;
    private FileTransportResult _result;

    private Timer _speedTimer;
    private long _totalDataLength;

    private BackgroundWorker _worker;

    public bool TransportInProgress { get; private set; }

    public event CurrentFileChangedEventHandler CurrentFileChanged;

    public event CurrentProgressChangedEventHandler CurrentProgressChanged;

    public event CurrentWriteSpeedUpdatedEventHandler CurrentWriteSpeedUpdated;

    public event TotalProgressChangedEventHandler TotalProgressChanged;

    public event TransportCompleteEventHandler TransportComplete;

    public void AddFile(string sourceFile, string destinationFile)
    {
        if (!File.Exists(sourceFile))
            throw new FileNotFoundException("The specified file does not exist!", sourceFile);

        var fileInfo = new FileInfo(sourceFile);

        _totalDataLength += fileInfo.Length;

        _sourceFiles.Add(sourceFile);
        _destinationFiles.Add(destinationFile);
    }

    public void BeginTransport()
    {
        // update the write speed every 3 seconds
        _speedTimer = new Timer {Interval = 3000};
        _speedTimer.Elapsed += SpeedTimerElapsed;

        _worker = new BackgroundWorker();
        _worker.DoWork += DoTransport;
        _worker.RunWorkerCompleted += WorkerCompleted;

        _worker.RunWorkerAsync();
        _speedTimer.Start();

        TransportInProgress = true;
    }

    private void SpeedTimerElapsed(object sender, ElapsedEventArgs e)
    {
        InvokeCurrentSpeedUpdated(_bytesCopiedSinceInterval);

        _bytesCopiedSinceInterval = 0;
    }

    private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        TransportInProgress = false;
        InvokeTransportComplete(_result);
    }

    public void CancelTransport(bool rollbackChanges)
    {
        if (TransportInProgress == false)
            throw new InvalidOperationException("You tried to stop the transport before you started it!");

        _result = FileTransportResult.Cancelled;

        _worker.CancelAsync();

        while (_worker.IsBusy)
        {
            // wait for worker to die an 'orrible death
        }

        // TODO: rollback changes if requested
    }

    private void DoTransport(object sender, DoWorkEventArgs e)
    {
        long totalBytesCopied = 0;
        int totalPercentComplete = 0;

        for (int i = 0; i < _sourceFiles.Count; i++)
        {
            string sourceFile = _sourceFiles[i];
            string destinationFile = _destinationFiles[i];

            long currentFileLength = new FileInfo(sourceFile).Length;

            InvokeCurrentFileChanged(sourceFile);

            using (var sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
            {
                using (var destinationStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write))
                {
                    using (var reader = new BinaryReader(sourceStream))
                    {
                        using (var writer = new BinaryWriter(destinationStream))
                        {
                            int lastPercentComplete = 0;

                            for (int j = 0; j < currentFileLength; j++)
                            {
                                writer.Write(reader.ReadByte());

                                totalBytesCopied += 1;
                                _bytesCopiedSinceInterval += 1;

                                int current = Convert.ToInt32((j/(double) currentFileLength)*100);
                                int total = Convert.ToInt32((totalBytesCopied/(double) _totalDataLength)*100);

                                // raise progress events every 3%
                                if (current%3 == 0)
                                {
                                    // only raise the event if the progress has increased
                                    if (current > lastPercentComplete)
                                    {
                                        lastPercentComplete = current;
                                        InvokeCurrentProgressChanged(lastPercentComplete);
                                    }
                                }

                                if (total%3 == 0)
                                {
                                    // only raise the event if the progress has increased
                                    if (total > totalPercentComplete)
                                    {
                                        totalPercentComplete = total;
                                        InvokeTotalProgressChanged(totalPercentComplete);
                                    }
                                }
                            }
                        }

                        InvokeCurrentProgressChanged(100);
                    }
                }
            }
        }

        InvokeTotalProgressChanged(100);
    }

    private void InvokeCurrentFileChanged(string fileName)
    {
        CurrentFileChangedEventHandler handler = CurrentFileChanged;

        if (handler == null) return;

        handler(fileName);
    }

    private void InvokeCurrentProgressChanged(int percentComplete)
    {
        CurrentProgressChangedEventHandler handler = CurrentProgressChanged;

        if (handler == null) return;

        handler(percentComplete);
    }

    private void InvokeCurrentSpeedUpdated(long bytesPerSecond)
    {
        CurrentWriteSpeedUpdatedEventHandler handler = CurrentWriteSpeedUpdated;

        if (handler == null) return;

        handler(bytesPerSecond);
    }

    private void InvokeTotalProgressChanged(int percentComplete)
    {
        TotalProgressChangedEventHandler handler = TotalProgressChanged;

        if (handler == null) return;

        handler(percentComplete);
    }

    private void InvokeTransportComplete(FileTransportResult result)
    {
        TransportCompleteEventHandler handler = TransportComplete;

        if (handler == null) return;

        handler(result);
    }
}

}

EDIT: Code added (GUI)

using System;
using System.IO;
using System.Windows.Forms;
using ExtensionMethods;
using nGenSolutions.IO;

namespace TestApplication
{
public partial class ProgressForm : Form
{
    public ProgressForm()
    {
        InitializeComponent();
    }

    private void ProgressForm_Load(object sender, EventArgs e)
    {
        var transporter = new FileTransporter();
        foreach (string fileName in Directory.GetFiles("C:\\Temp\\"))
        {
            transporter.AddFile(fileName, "C:\\" + Path.GetFileName(fileName));
        }

        transporter.CurrentFileChanged += transporter_CurrentFileChanged;
        transporter.CurrentProgressChanged += transporter_CurrentProgressChanged;
        transporter.TotalProgressChanged += transporter_TotalProgressChanged;
        transporter.CurrentWriteSpeedUpdated += transporter_CurrentWriteSpeedUpdated;
        transporter.TransportComplete += transporter_TransportComplete;

        transporter.BeginTransport();
    }

    void transporter_TransportComplete(FileTransportResult result)
    {
        Close();
    }

    void transporter_CurrentWriteSpeedUpdated(long bytesPerSecond)
    {
        double megaBytesPerSecond = (double)bytesPerSecond/1024000;

        currentSpeedLabel.SafeInvoke(x=> x.Text = string.Format("Transfer speed: {0:0.0} MB/s", megaBytesPerSecond));
    }

    private void transporter_TotalProgressChanged(int percentComplete)
    {
        totalProgressBar.SafeInvoke(x => x.Value = percentComplete);
    }

    private void transporter_CurrentProgressChanged(int percentComplete)
    {
        currentProgressBar.SafeInvoke(x => x.Value = percentComplete);
    }

    private void transporter_CurrentFileChanged(string fileName)
    {
        this.SafeInvoke(x => x.Text = string.Format("Current file: {0}", fileName));
    }
}

}

EDIT: SafeInvoke code added

public static void SafeInvoke<T>(this T @this, Action<T> action) where T : Control
    {
        if (@this.InvokeRequired)
        {
            @this.Invoke(action, new object[] {@this});
        }
        else
        {
            if (!@this.IsHandleCreated) return;

            if (@this.IsDisposed)
                throw new ObjectDisposedException("@this is disposed.");

            action(@this);
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T03:22:32+00:00Added an answer on May 23, 2026 at 3:22 am

    Well, if transporter_CurrentProgressChanged gets correct values, the program works properly. You can try to add some minimal Thread.Sleep call to InvokeCurrentProgressChanged (maybe with 0 parameter) when progress value is 100%, to get UI chance to update itself, but in this case you reduce the program performance. It is possibly better to leave the program unchanged, since it works as expected, and main progress bar is updated.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
i want to parse a xhtml file and display in UITableView. what is the
I have thousands of HTML files to process using Groovy/Java and I need to
I have a reasonable size flat file database of text documents mostly saved in
I'm parsing an XML file, the creators of it stuck in a bunch social

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.