Beispiel #1
0
 private void OnProgressCall(ProgressCall call, long length, long position)
 {
     if (call != null)
     {
         try { call(length, position); }
         catch { }
     }
 }
Beispiel #2
0
        /// <summary>
        /// DownloadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="formData"></param>
        /// <param name="saveFileName"></param>
        /// <param name="call"></param>
        /// <returns></returns>
        public EmptyContent DownloadFile(string url, string method, FormData formData, string saveFileName, ProgressCall call)
        {
            EmptyContent result = new EmptyContent();

            try
            {
                HttpWebRequest request = this.CreateRequest(url, method);
                this.SetFormData(request, formData);
                using (HttpWebResponse response = this.GetResponse(request))
                {
                    using (var responseStream = this.GetResponseStream(response))
                    {
                        long length   = response.ContentLength > 0 ? response.ContentLength : responseStream.Length;
                        long position = 0;
                        this.OnProgressCall(call, length, position);
                        using (var fs = File.Create(saveFileName))
                        {
                            byte[] buffer   = new byte[8 * 1024];
                            int    count    = 0;
                            int    trycount = 0;
                            do
                            {
                                count = responseStream.Read(buffer, 0, buffer.Length);
                                if (count > 0)
                                {
                                    fs.Write(buffer, 0, count);
                                    fs.Flush();
                                    position = position + count;
                                    trycount = 0;
                                    this.OnProgressCall(call, length, position);
                                }
                                else if ((response.ContentLength == 0 || response.ContentLength > position) &&
                                         trycount < 3)
                                {
                                    System.Threading.Thread.Sleep(50);
                                    trycount++;
                                    count = 1;
                                }
                            }while (count > 0);
                        }
                        this.SetContent(response, result);
                    }
                }
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }

            return(result);
        }