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 7751209
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T11:29:20+00:00 2026-06-01T11:29:20+00:00

Have been reading about async and tasks and been attempting to convert the CopyFileEx

  • 0

Have been reading about async and tasks and been attempting to convert the CopyFileEx method via PInvoke to the Task pattern with progress. I am having issues with the progress part.

CopyFileEx has a callback called CopyProgressRoutine which has a parameter called lpData that takes a pointer. I thought i could use this to pass around my IProgress interface so I could report progress. However, turns out I have to use a structure, not a class. Any ideas how I can get this working, OR am I heading in the completely wrong direction with this one?

public class ProgressReportAsync
{
    public int PercentDone { get; set; }
    public string InfoText { get; set; }

    public void setProgress(long _progress, long _total)
    {
        PercentDone = Convert.ToInt32((_progress * 100) / _total);
        InfoText = PercentDone + "% complete."; ;
    }
}

class FileCopyAsync
{
    class UserCallbackArg
    {
        public CancellationToken ct;
        public IProgress<ProgressReportAsync> prg;

        public UserCallbackArg(CancellationToken _ct, IProgress<ProgressReportAsync> _prg)
        {
            ct = _ct;
            prg = _prg;
        }

        public UserCallbackArg() { }
    }

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, Object lpData, ref bool pbCancel, CopyFileFlags dwCopyFlags);

    private delegate CopyProgressResult CopyProgressRoutine(long TotalFileSize, long TotalBytesTransferred,
        long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, CopyProgressCallbackReason dwCallbackReason,
        IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData);

    [Flags]
    enum CopyFileFlags : uint
    {
        COPY_FILE_FAIL_IF_EXISTS = 0x00000001,
        COPY_FILE_RESTARTABLE = 0x00000002,
        COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,
        COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008,
        COPY_FILE_COPY_SYMLINK = 0x00000800,
        COPY_FILE_NO_BUFFERING = 0x00001000
    }

    enum CopyProgressResult : uint
    {
        PROGRESS_CONTINUE = 0,
        PROGRESS_CANCEL = 1,
        PROGRESS_STOP = 2,
        PROGRESS_QUIET = 3
    }

    enum CopyProgressCallbackReason : uint
    {
        CALLBACK_CHUNK_FINISHED = 0x00000000,
        CALLBACK_STREAM_SWITCH = 0x00000001
    }

    private static bool m_bCancel;

    private CopyProgressResult CopyProgressHandler(long total, long transferred, long streamSize, long StreamByteTrans, uint dwStreamNumber, CopyProgressCallbackReason reason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
    {
        switch (reason)
        {
            case CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED:

                UserCallbackArg ucarg = (UserCallbackArg)Marshal.PtrToStructure(lpData, typeof(UserCallbackArg));

                IProgress<ProgressReportAsync> prg = ucarg.prg;
                ProgressReportAsync prgReport = new ProgressReportAsync();

                prgReport.setProgress(transferred, total);
                prg.Report(prgReport);

                if (ucarg.ct.IsCancellationRequested)
                {
                    m_bCancel = true;
                }

                return m_bCancel ? CopyProgressResult.PROGRESS_CANCEL : CopyProgressResult.PROGRESS_CONTINUE;

            default:
                return CopyProgressResult.PROGRESS_CONTINUE;
        }
    }

    public FileCopyAsync() { }

    public Task DoWorkAsync(string _from, string _to, CancellationToken ct, IProgress<ProgressReportAsync> prg)
    {
        return TaskEx.Run(() =>
        {
            bool copyResult;

            if (File.Exists(_to))
            {
                //throw new Exception("File already exists: " + _to);
            }

            if (!File.Exists(_from))
            {
                throw new FileNotFoundException(_from);
            }

            FileInfo fi = new FileInfo(_from);

            m_bCancel = false;

            UserCallbackArg ucarg = new UserCallbackArg(ct, prg);
            GCHandle handle = GCHandle.Alloc(ucarg, GCHandleType.Pinned);
            IntPtr ptr = handle.AddrOfPinnedObject();


            if (fi.Length > (1024 * 1024 * 100))
            {
                //Greater than 100mb then no buffer flag added
                copyResult = CopyFileEx(_from, _to, new CopyProgressRoutine(CopyProgressHandler), ptr, ref m_bCancel, (CopyFileFlags.COPY_FILE_RESTARTABLE & CopyFileFlags.COPY_FILE_FAIL_IF_EXISTS & CopyFileFlags.COPY_FILE_NO_BUFFERING));
            }
            else
            {
                copyResult = CopyFileEx(_from, _to, new CopyProgressRoutine(CopyProgressHandler), ptr, ref m_bCancel, (CopyFileFlags.COPY_FILE_RESTARTABLE & CopyFileFlags.COPY_FILE_FAIL_IF_EXISTS));
            }
            if (!copyResult)
            {
                int error = Marshal.GetLastWin32Error();

                if (m_bCancel && (error == 1235))
                {
                    return;
                }
                else
                {
                    Win32Exception ex = new Win32Exception(error);
                    throw new Win32Exception(error);
                }
            }
        });
    }
}
  • 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-06-01T11:29:22+00:00Added an answer on June 1, 2026 at 11:29 am

    I think the easiest solution is to move the CopyProgressHandler callback to your user arguments class. In that case you can use ucarg.CopyProgressHandler as your CopyProgressRoutine and invoke methods on the IProgress reference you stored in your user arguments class. Probably you can move the m_bCancel flag to that class too.

    With this approach you are avoiding the marshalling of your data.

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

Sidebar

Related Questions

I have been reading about using Sharp Architecture to control nhiberate via Wcf. Is
I have been reading about the responsive web pattern and I have successfully implemented
I have been reading about Factory pattern a lot lately. I am trying to
I have been reading about the thread-pool pattern and I can't seem to find
I have been reading about collision detection in games on stackoverflow and other sites.
I have been reading about the continuation passing style programming technique (C# 3.0 implementation).
I have been reading about Quicksort and found that sometimes it' s referred to
I have been reading about Scala for a while and even wrote some small
i have been reading about multiple inheritance What is the exact problem with multiple
I have been reading about unsafePerformIO lately, and I would like to ask you

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.