C# 我如何知道在文件下载完成时使用httpwebrequest和webresponse?

C# 我如何知道在文件下载完成时使用httpwebrequest和webresponse?,c#,.net,winforms,C#,.net,Winforms,嫁妆活动 private BackgroundWorker bgwDownloader = new BackgroundWorker(); 那么 downloader.FileDownloadSucceeded += new EventHandler(downloader_Succeeded); 问题是,当我在事件的最后一行中放置断点时,RichTextBoxExtensions就好像它只到达一次一样。下载的文件大小为0字节。然后,我再次使continue停止,这次文件完全下载或写入到正确的

嫁妆活动

private BackgroundWorker bgwDownloader = new BackgroundWorker();
那么

downloader.FileDownloadSucceeded += new EventHandler(downloader_Succeeded);
问题是,当我在事件的最后一行中放置断点时,RichTextBoxExtensions就好像它只到达一次一样。下载的文件大小为0字节。然后,我再次使continue停止,这次文件完全下载或写入到正确的大小

所以我需要在这个事件中检查它何时完成下载。 我怎么做

在此事件中,我想对下载的文件进行一些操作,但我需要确保文件已下载完成,并且我现在使用断点进行了检查,只有在第二次到达事件时,文件才完成下载/写入硬盘

更新

我的主要目标是将此方法添加到form1中

private void downloader_Succeeded(object sender, EventArgs e)
        {
            countFilesDownloaded++;
            label6.Text = countFilesDownloaded.ToString();
            RichTextBoxExtensions.UpdateText(richTextBox1, "Ready: ", "Downloaded: ", Color.Green);
        }
事件

Image img = new Bitmap(downloader.fileName);
我在文件名中看到:C:\New folder(3)\Countries\Europe\07032017\u 223558\Europe--07032017\u 223558384.gif

该文件存在于硬盘上。但我在这一行遇到了一个例外:

private void downloader_Succeeded(object sender, EventArgs e)
        {
            countFilesDownloaded++;
            label6.Text = countFilesDownloaded.ToString();
            RichTextBoxExtensions.UpdateText(richTextBox1, "Ready: ", "Downloaded: ", Color.Green);
            Image img = new Bitmap(downloader.fileName);
        }
这是backgroundworker的完整类:

这是我使用winrar的项目:


据我所知,文件下载完成后会触发一个事件

Image img = new Bitmap(downloader.fileName);

System.Reflection.TargetInvocationException was unhandled
  HResult=-2146232828
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at DownloaderPro.Program.Main() in C:\Users\Chocolade\Documents\Visual Studio 2015\Projects\DownloaderPro\DownloaderPro\DownloaderPro\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2147024809
       Message=Parameter is not valid.
       Source=System.Drawing
       StackTrace:
            at System.Drawing.Bitmap..ctor(String filename)
            at DownloaderPro.Form1.downloader_Succeeded(Object sender, EventArgs e) in C:\Users\Chocolade\Documents\Visual Studio 2015\Projects\DownloaderPro\DownloaderPro\DownloaderPro\Form1.cs:line 347
            at DownloaderPro.FileDownloader.bgwDownloader_ProgressChanged(Object sender, ProgressChangedEventArgs e) in C:\Users\Chocolade\Documents\Visual Studio 2015\Projects\DownloaderPro\DownloaderPro\DownloaderPro\FileDownloader.cs:line 549
            at System.ComponentModel.BackgroundWorker.OnProgressChanged(ProgressChangedEventArgs e)
            at System.ComponentModel.BackgroundWorker.ProgressReporter(Object arg)
       InnerException: 
创建backgroundworker时只需订阅即可

编辑:

您只上传了sln文件。那里没什么可看的。 看了FileDownloader.cs的代码后,看起来你并不是自己写这个“怪物”的

我想建议一种不同的方法:

fireEventFromBgw(Event.FileDownloadSucceeded)
其中source是url,目标是下载到的路径。对于简单的图片,它应该做到这一点。这种方法是同步的

之后:

 WebClient client = new WebClient();
 client.DownloadFile(source, target);

对于多个文件,将所有文件放在一个循环中。

您可能需要查看BackgroundWorker的ReportProgress和OnReportProgress事件。它需要一个ProgressChangedEventArgs,它有一个名为UserState的对象属性,您可以传回信息(比如一个表示“文件‘X’已完成下载”的字符串)。因此,当WebRequest完成时,请提交ReportProgress。是的,我忘了提到我已经以Form1订阅了此活动。如果您能在问题中看到我更新的部分,我现在用此部分更新了我的问题。我现在使用了断点,发现了问题所在,但不确定如何处理。似乎是在问题到达e时仅在文件写入或完成下载两次后才释放。第一次下载文件时,文件大小为9字节,有时为12kb或其他大小,但只有在第二次文件大小正确时才释放。现在我重试,现在每次下载一个文件时,它只会到达事件一次。而文件大小正确ems在硬盘上没有问题。不确定发生了什么。我将再次更新我的问题,说明我的主要目标是什么。好的,上次更新了我的问题。对此表示抱歉。现在,我正在尝试在事件中做什么,以及我遇到了什么异常。从一开始,整个问题就是异常。而且,有时它甚至会达到平衡下载完成,但有时我看到文件大小为0字节,只有在第二次到达事件时,文件才正常。不知道为什么。但是如果我在这个事件中根本不使用断点,让程序继续工作,所有文件都正常。所以我想知道这个事件到底发生了什么?怎么了w来解决它。@DanielHalfoni在引发事件的位置放置一个断点,并检查文件的状态。事件不应引发多次。请提供创建Backgroundworker或上载项目的完整类,以便我们看到它的作用。我在底部的两个链接中添加了我的问题,一个链接用于类FileDownlo第二个链接是我的项目-完整的项目
Image img = new Bitmap(downloader.fileName);

System.Reflection.TargetInvocationException was unhandled
  HResult=-2146232828
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at DownloaderPro.Program.Main() in C:\Users\Chocolade\Documents\Visual Studio 2015\Projects\DownloaderPro\DownloaderPro\DownloaderPro\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2147024809
       Message=Parameter is not valid.
       Source=System.Drawing
       StackTrace:
            at System.Drawing.Bitmap..ctor(String filename)
            at DownloaderPro.Form1.downloader_Succeeded(Object sender, EventArgs e) in C:\Users\Chocolade\Documents\Visual Studio 2015\Projects\DownloaderPro\DownloaderPro\DownloaderPro\Form1.cs:line 347
            at DownloaderPro.FileDownloader.bgwDownloader_ProgressChanged(Object sender, ProgressChangedEventArgs e) in C:\Users\Chocolade\Documents\Visual Studio 2015\Projects\DownloaderPro\DownloaderPro\DownloaderPro\FileDownloader.cs:line 549
            at System.ComponentModel.BackgroundWorker.OnProgressChanged(ProgressChangedEventArgs e)
            at System.ComponentModel.BackgroundWorker.ProgressReporter(Object arg)
       InnerException: 
fireEventFromBgw(Event.FileDownloadSucceeded)
 WebClient client = new WebClient();
 client.DownloadFile(source, target);
var frames = GetFramesFromAnimatedGIF(new Bitmap(target));