2017-03-07 11 views
0
private void downloadFile(Int32 fileNr) 
     { 
      FileStream writer = null; 
      m_currentFileSize = 0; 
      fireEventFromBgw(Event.FileDownloadAttempting); 

      FileInfo file = this.Files[fileNr]; 
      FileInfo fileFirstDateTime = this.Files[0]; 
      FileInfo fileLastDateTime = this.Files[19]; 
      Int64 size = 0; 

      Byte[] readBytes = new Byte[this.PackageSize]; 
      Int32 currentPackageSize; 
      System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch(); 
      Int32 readings = 0; 
      Exception exc = null; 
      writer = LocalDirectorySettings(file); 
      HttpWebRequest webReq; 
      HttpWebResponse webResp = null; 

      try 
      { 
       webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path); 
       webResp = (HttpWebResponse)webReq.GetResponse(); 

       size = webResp.ContentLength; 
      } 
      catch (Exception ex) { exc = ex; } 

      m_currentFileSize = size; 
      fireEventFromBgw(Event.FileDownloadStarted); 

      if (exc != null) 
      { 
       bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc); 
      } 
      else 
      { 
       m_currentFileProgress = 0; 
       while (m_currentFileProgress < size && !bgwDownloader.CancellationPending) 
       { 
        while (this.IsPaused) { System.Threading.Thread.Sleep(100); } 

        speedTimer.Start(); 

        currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize); 

        m_currentFileProgress += currentPackageSize; 
        m_totalProgress += currentPackageSize; 
        fireEventFromBgw(Event.ProgressChanged); 
        try 
        { 
         writer.Write(readBytes, 0, currentPackageSize); 
        } 
        catch(Exception eee) 
        { 
         string myeee = eee.ToString(); 
        } 
        readings += 1; 

        if (readings >= this.StopWatchCyclesAmount) 
        { 
         m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000/(speedTimer.ElapsedMilliseconds + 1)); 
         speedTimer.Reset(); 
         readings = 0; 
        } 
       } 

       speedTimer.Stop(); 
       writer.Close(); 
       webResp.Close(); 
       if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); } 
      } 
      fireEventFromBgw(Event.FileDownloadStopped); 
     } 

bgwDownloaderファイルのダウンロードが完了したら、httpwebrequestとwebresponseを使ってどのように知っていますか?

private BackgroundWorker bgwDownloader = new BackgroundWorker(); 

doworkイベント、それはすべてのファイルが完了しダウンロードするだけで完了したイベントになってきたのBackgroundWorker完了した場合には

private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e) 
     { 
      Int32 fileNr = 0; 
      countFilesNames = 0; 

      if (this.SupportsProgress) { calculateFilesSize(); } 

      if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); } 

      while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending) 
      { 
       m_fileNr = fileNr; 
       downloadFile(fileNr); 

       if (bgwDownloader.CancellationPending) 
       { 
        fireEventFromBgw(Event.DeletingFilesAfterCancel); 
        cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1); 
       } 
       else 
       { 
        fileNr += 1; 
       } 
      } 
     } 

しかし、私は各ファイルのダウンロードが完了するたびにイベントを作成する必要があります。 私はbackgroundworkerまたはhttpwebrequest webrespondeと何とかしなくてもいいですか?そしてどうやって ?

もし必要ならば、私はクラス全体を少しアップロードします。

更新

これは私がFileDownloadSucceededイベントをサブスクライブする方法をForm1にあります

downloader.FileDownloadSucceeded += new EventHandler(downloader_Succeeded); 

はその後イベント

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

での問題は、私は、イベント内でブレークポイントを置くときであります最後の行にはRichTextBoxExtensionsが一度そこに来るようです。ダウンロードしたファイルは0バイトサイズです。それから私はこのイベントでもう一度この時間をもう一度止めます。今回は、ファイルが完全にダウンロードまたは書かれた正しいサイズになっています。

ダウンロードが完了したら、このイベントを何らかの形でチェックする必要があります。 どうすればいいですか?

このイベントでダウンロードしたファイルを操作したいのですが、ファイルがダウンロードされたことを確認する必要があります。そして、今すぐブレークポイントでチェックして、イベントにファイルを取得していますハードディスクにダウンロード/書き込まれます。

更新

すべて抽出するために、ダウンロードされた各ファイルは、/ファイルからのフレームのGIF画像を解析することをここに私の主な目標は、私が

public static Image[] GetFramesFromAnimatedGIF(Image IMG) 
     { 
      List<Image> IMGs = new List<Image>(); 
      int Length = IMG.GetFrameCount(FrameDimension.Time); 

      for (int i = 0; i < Length; i++) 
      { 
       IMG.SelectActiveFrame(FrameDimension.Time, i); 
       IMGs.Add(new Bitmap(IMG)); 
       IMG.Dispose(); 
      } 

      return IMGs.ToArray(); 
     } 

をForm1に、このメソッドを追加したことであると私はしたいです

Image img = new Bitmap(downloader.fileName); 

イベント

:私は、行の前に追加FileDownloadSucceededイベントでのように、ファイルは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); 
     } 

:C:新しいフォルダ\(3)\国\ヨーロッパ\ 07032017_223558ヨーロッパ\ --- 07032017_223558384.gif

ファイルがハードディスク上に存在しています。しかし、私は、このライン上の例外を取得しています:

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のと完全なクラスです:

Class FileDownloader

そして、これは私がWinRARのを使用したプロジェクトである:

Project

+1

BackgroundWorkerのReportProgressイベントとOnReportProgressイベントを確認することができます。 "File 'X'がダウンロードを完了したことを示す文字列のように、情報を渡すことができるUserStateというオブジェクトプロパティを持つProgressChangedEventArgsが必要ですので、WebRequestが終了したらReportProgressを発生させてください –

答えて

1

私が見る限り、filedownloadが完了した時点でイベントが発生しています。

fireEventFromBgw(Event.FileDownloadSucceeded) 

あなたのbackgroundworkerを作成するときに登録するだけです。

編集:

slnファイルのみをアップロードしました。それほど多くは見えません。 FileDownloader.csのコードを調べた後、自分でこの "モンスター"を書いていないようです。ソースがURLであるとにダウンロードするためのパスをターゲット

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

I'dは異なるapprouchを提案したいです。簡単な写真の場合は、そのトリックを行う必要があります。 Thrustは同期しています。その後

var frames = GetFramesFromAnimatedGIF(new Bitmap(target)); 

複数のファイルに対しては、ループ内のすべて置きます。

+0

はい、私は購読しているこのイベントは既にForm1になっています。私は質問の中で私の更新された部分を見ることができるならば、この部分で私の質問を更新しました。イベントが2回だけになると、FileDownloadSucceededに到達したときに初めてファイルが書き込まれたりダウンロードが終了したりします。ファイルは9バイト、時には12kbなどのサイズですが、2回目にはファイルが右側にありますサイズは –

+0

もう一度やり直してみましたが、今度はファイルがダウンロードされるたびに1回しかイベントに出てこないのですが、ファイルはハードディスク上で問題ないと思われます。私の主な目標は私の質問をもう一度更新するでしょう。 –

+0

最後に私の質問が更新されました。そのために残念。今私がイベントで何をしようとしているのか、何が例外になっているのかで最初からの問題はすべて例外でした。また、イベントに遭遇し、ファイルが正常にダウンロードされることもありますが、ファイルが0バイトのサイズで、ファイルが正常であるというイベントに2回目のときにのみ表示されることがあります。理由は分かりません。しかし、私はこのイベントでブレークポイントを全く使用しておらず、プログラムが正常に動作し続けることができれば、すべてのファイルは正常です。だから私はこのイベントで何が起こっているのだろうか?そしてそれを解決する方法。 –

関連する問題