Exemple #1
0
        /// <summary>
        /// 附件下载
        /// </summary>
        /// <param name="infoUrl"></param>
        private void AddBaseFile(string infoUrl, string strFileName, CorpPunish info)
        {
            string strFileUrl  = ToolDb.DbServerPath + "SiteManage\\Files\\Corp_Attach\\";
            string strFile     = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "\\"; //新建文件夹地址
            long   lStartPos   = 0;                                                                   //返回上次下载字节
            long   lCurrentPos = 0;                                                                   //返回当前下载文件长度
            long   lDownLoadFile;                                                                     //返回当前下载文件长度

            System.IO.FileStream fs;
            long length = 0;

            if (System.IO.File.Exists(strFileUrl + strFile))
            {
                fs        = System.IO.File.OpenWrite(strFileUrl + strFile);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
            }
            else
            {
                Directory.CreateDirectory(strFileUrl + strFile);
                fs        = new FileStream(strFileUrl + strFile + strFileName, System.IO.FileMode.OpenOrCreate);
                lStartPos = 0;
            }
            try
            {
                System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create(infoUrl) as System.Net.HttpWebRequest;
                length        = request.GetResponse().ContentLength;
                lDownLoadFile = length;
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos);
                }
                System.IO.Stream ns     = request.GetResponse().GetResponseStream();
                byte[]           nbytes = new byte[102];
                int nReadSize           = 0;
                nReadSize = ns.Read(nbytes, 0, 102);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize   = ns.Read(nbytes, 0, 102);
                    lCurrentPos = fs.Length;
                }
                fs.Close();
                ns.Close();
                if (length > 1024)
                {
                    BaseAttach baseInfo = ToolDb.GenBaseAttach(ToolDb.NewGuid, strFileName, info.Id, strFile + strFileName, length.ToString(), "");
                    ToolDb.SaveEntity(baseInfo, string.Empty);
                }
                else
                {
                    File.Delete(strFileUrl + strFile + strFileName);
                }
            }
            catch
            {
                fs.Close();
                File.Delete(strFileUrl + strFile + strFileName);
            }
        }
Exemple #2
0
        public long lDownloadFile;   //返回当前下载文件长度

        public bool Download()
        {
            bool Error = false;

            System.IO.FileStream fs;
            if (System.IO.File.Exists(StrFileName))
            {
                fs        = System.IO.File.OpenWrite(StrFileName);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
                //移动文件流中的当前指针
            }
            else
            {
                fs        = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
                lStartPos = 0;
            }

            //打开网络连接
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
                long length = request.GetResponse().ContentLength;
                lDownloadFile = length;
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos); //设置Range值
                }
                //向服务器请求,获得服务器回应数据流
                System.IO.Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes    = new byte[512];
                int    nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 512);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize   = ns.Read(nbytes, 0, 512);
                    lCurrentPos = fs.Length;
                }

                fs.Close();
                ns.Close();
                strError = "下载完成";
                Error    = true;
            }
            catch (Exception ex)
            {
                fs.Close();
                strError = "下载过程中出现错误:" + ex.ToString();
                Error    = false;
            }
            return(Error);
        }
Exemple #3
0
        private bool downfile(string url, string LocalPath)
        {
            string StrUrl      = url;       //文件下载网址
            string StrFileName = LocalPath; //下载文件保存地址
            long   lStartPos   = 0;         //返回上次下载字节
            long   lCurrentPos = 0;         //返回当前下载字节
            long   lDownloadFile;           //返回当前下载文件长度

            System.IO.FileStream fs;
            if (System.IO.File.Exists(StrFileName))
            {
                System.IO.File.Delete(StrFileName);
                //lStartPos = fs.Length;
                //fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
                //移动文件流中的当前指针
            }
            else
            {
                //fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
                lStartPos = 0;
            }
            fs        = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
            lStartPos = 0;
            try {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
                long length = request.GetResponse().ContentLength;
                lDownloadFile = length;
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos); //设置Range值
                }
                //向服务器请求,获得服务器回应数据流
                System.IO.Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes    = new byte[512];
                int    nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 512);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize   = ns.Read(nbytes, 0, 512);
                    lCurrentPos = fs.Length;
                }

                fs.Close();
                ns.Close();
                return(true);
            } catch {
                return(false);
            } finally {
                fs.Close();
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        bool DownloadFiles(string downloadPath, string Fname)
        {
            System.Net.HttpWebRequest LHttpWebRequest = null;
            Stream LStreamResponse = null;

            System.IO.FileStream LStreamCertificateFile = null;
            Fname = downloadPath.Substring(downloadPath.LastIndexOf(Fname));
            string LStrFileFullName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Fname);
            string ServerPath       = System.IO.Path.Combine(string.Format("http://{0}:{1}", CurrentApp.Session.AppServerInfo.Address, CurrentApp.Session.AppServerInfo.Port - 1), downloadPath);

            //string path = System.IO.Path.Combine(string.Format("http://192.168.4.166:8081"), downloadPath);
            ServerPath = ServerPath.Replace("\\", "/");
            try
            {
                LStreamCertificateFile = new FileStream(LStrFileFullName, FileMode.Create);
                LHttpWebRequest        = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(ServerPath);
                long LContenctLength = LHttpWebRequest.GetResponse().ContentLength;
                LHttpWebRequest.AddRange(0);
                LStreamResponse = LHttpWebRequest.GetResponse().GetResponseStream();

                byte[] LbyteRead      = new byte[1024];
                int    LIntReadedSize = LStreamResponse.Read(LbyteRead, 0, 1024);
                while (LIntReadedSize > 0)
                {
                    LStreamCertificateFile.Write(LbyteRead, 0, LIntReadedSize);
                    LIntReadedSize = LStreamResponse.Read(LbyteRead, 0, 1024);
                }
                LStreamCertificateFile.Close(); LStreamCertificateFile.Dispose();
            }
            catch (Exception ex)
            {
                CurrentApp.WriteLog("DownLoad File To Disk  Failed.", string.Format("FileName : {0} \t  SavePath : {1} \t   ServerPath :{2} \t  Message :{3}", Fname, LStrFileFullName, ServerPath, ex.Message));
                ShowException(ex.Message);
                return(false);
            }
            finally
            {
                if (LHttpWebRequest != null)
                {
                    LHttpWebRequest.Abort();
                }
                if (LStreamResponse != null)
                {
                    LStreamResponse.Close(); LStreamResponse.Dispose();
                }
                if (LStreamCertificateFile != null)
                {
                    LStreamCertificateFile.Close(); LStreamCertificateFile.Dispose();
                }
            }
            CurrentApp.WriteLog("DownLoad File To Disk  Sucessed!", string.Format("SavePath : {0} \t   ServerPath :{1} \t  ", LStrFileFullName, ServerPath));
            return(true);
        }
        public bool DownLoadFile(string localPath, string hostURL, int byteCount, string userID, long cruuent)
        {
            bool result = true;


            string tmpURL = hostURL;

            byteCount = byteCount * 1024;
            hostURL   = tmpURL + "&npos=" + cruuent.ToString();

            System.IO.FileStream fs;
            fs = new FileStream(localPath, FileMode.OpenOrCreate);
            if (cruuent > 0)
            {
                //偏移指针
                fs.Seek(cruuent, System.IO.SeekOrigin.Current);
            }


            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(hostURL);
            if (cruuent > 0)
            {
                request.AddRange(Convert.ToInt32(cruuent));    //设置Range值
            }

            try
            {
                //向服务器请求,获得服务器回应数据流
                System.IO.Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes    = new byte[byteCount];
                int    nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, byteCount);

                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize = ns.Read(nbytes, 0, byteCount);
                }
                fs.Close();
                ns.Close();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorMsg("下载" + localPath + "的时候失败!" + "原因是:", ex.Message);
                fs.Close();
                result = false;
            }


            return(result);
        }
Exemple #6
0
        public long DownLoadFile()
        {
            System.IO.FileStream fs;
            long length = 0;

            if (System.IO.File.Exists(strFileUrl + strFile))
            {
                fs        = System.IO.File.OpenWrite(strFileUrl + strFile);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
            }
            else
            {
                Directory.CreateDirectory(strFileUrl + strFile);
                fs        = new FileStream(strFileUrl + strFile + strFileName, System.IO.FileMode.OpenOrCreate);
                lStartPos = 0;
            }
            try
            {
                System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create(strUrl) as System.Net.HttpWebRequest;
                length        = request.GetResponse().ContentLength;
                lDownLoadFile = length;
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos);
                }
                System.IO.Stream ns     = request.GetResponse().GetResponseStream();
                byte[]           nbytes = new byte[102];
                int nReadSize           = 0;
                nReadSize = ns.Read(nbytes, 0, 102);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize   = ns.Read(nbytes, 0, 102);
                    lCurrentPos = fs.Length;
                }
                fs.Close();
                ns.Close();
                if (length < 1024)
                {
                    File.Delete(strFileUrl + strFile + strFileName);
                }
                strError = "下载完成";
            }
            catch
            {
                fs.Close();
                File.Delete(strFileUrl + strFile + strFileName);
                strError = "下载过程中出现错误";
            }
            return(length);
        }
Exemple #7
0
        public static void ResumeRetry(string Url)
        {
            bool   UseProxy      = true;
            string ProxyServer   = "";
            int    ProxyPort     = 8080;
            string ProxyUsername = "";
            string ProxyPassword = "";


            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url);
            if (UseProxy)
            {
                request.Proxy = new System.Net.WebProxy(ProxyServer + ":" + ProxyPort.ToString());
                if (ProxyUsername.Length > 0)
                {
                    request.Proxy.Credentials = new System.Net.NetworkCredential(ProxyUsername, ProxyPassword);
                }
            }


            byte[] ba        = System.IO.File.ReadAllBytes("partial");
            int    BytesRead = ba.Length;
            bool   resuming  = false;

            //HttpWebRequest hrequest = (HttpWebRequest)request;
            //hrequest.AddRange(BytesRead); ::TODO: Work on this
            if (BytesRead > 0)
            {
                resuming = true;
                request.AddRange(BytesRead);
            }

            System.Net.WebResponse response = request.GetResponse();

            //result.MimeType = response.ContentType;
            //result.LastModified = response.LastModified;
            if (!resuming)//(Size == 0)
            {
                //resuming = false;
                int Size     = (int)response.ContentLength;
                int SizeInKB = (int)Size / 1024;
            }

            bool acceptRanges = string.Compare(response.Headers["Accept-Ranges"], "bytes", true) == 0;

            // Create network stream
            System.IO.Stream ns = response.GetResponseStream();
        }
Exemple #8
0
        /// <summary>
        /// Main download method.
        /// </summary>
        private async void download()
        {
            dlTimer.Start();
            dsTimer.Start();
            // Set 'cancelDownload' to false, so that method can stop again.
            cancelDownload = false;

            req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            // check if downloaded-length!=0 and !overwrite so the user want to resume.
            if (dLength > 0 && !overwrite)
            {
                req.AddRange(dLength);      // add range to the 'req' to change the point of start download.
            }
            isDownloading = true;
            using (res = (System.Net.HttpWebResponse) await req.GetResponseAsync())
            {
                fLength = res.ContentLength + dLength;                                                 // get the total-size of the file.
                eSize.Invoke(null, Unkdevt.StringHelpers.GetLengthString(FileSize));                   // update the total-size.
                eDownloadedSize.Invoke(null, Unkdevt.StringHelpers.GetLengthString(DownloadedLength)); // update the downloaded-length.
                dt = System.DateTime.Now;                                                              // get the current time ( point of start downloading ).
                using (stream = res.GetResponseStream())
                {
                    await System.Threading.Tasks.Task.Run(() =>     // await task so the winform don't freezing.
                    {
                        // update the download-state.
                        eDownloadState.Invoke(null, "Downloading");
                        // while not 'cancelDownload' and file doesn't end do:
                        while (!cancelDownload && ((bufferReader = stream.Read(buffer, 0, buffer.Length)) > 0))
                        {
                            fStream.Write(buffer, 0, bufferReader); // write byte to the file on harddisk.
                            dLength += bufferReader;                // update downloaded-length value.
                            cLength += bufferReader;                // update current-downloaded-length value.
                        }
                    });
                }
            }
            dlTimer.Stop();
            dsTimer.Stop();
            isDownloading = false;
            // eSpeed.Invoke(null, "0.0 Kb/s");    // update downloading-speed to 0.0 kb/s.
            eDownloadedSize.Invoke(null, Unkdevt.StringHelpers.GetLengthString(DownloadedLength)); // update downloaded-size.
            eDownloadState.Invoke(null, DownloadState);                                            // update download-state.
            fStream.Dispose();                                                                     // free file on harddisk by dispose 'fStream'.
        }
Exemple #9
0
 public void AddRange(int range)
 {
     _webRequest.AddRange(range);
 }
Exemple #10
0
        /// <summary>
        /// バックグラウンドスレッドでファイルのダウンロードを行う
        /// </summary>
        /// <param name="url">ダウンロードするURL</param>
        /// <param name="downloadToPath">ダウンロード先のディレクトリ名</param>
        protected void DownloadFile(string url, string downloadToPath)
        {
            string downloadFileName = Path.GetFileName(url);

            downloadFileName = ChangeFileInvalidChar(downloadFileName);
            string downloadFileFullName = Path.Combine(downloadToPath, downloadFileName);
            string downloadTempName     = downloadFileFullName + ".tmp";

            //If-Rangeヘッダに渡すエンティティタグを指定するときは指定する
            string entityTag = "";

            //WebRequestの作成
            System.Net.HttpWebRequest webreq =
                (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

            //ファイルがあればダウンロードが途中であると判断し、
            //ファイルサイズを取得する
            long firstPos;

            if (System.IO.File.Exists(downloadTempName))
            {
                firstPos = (new System.IO.FileInfo(downloadTempName)).Length;
            }
            else
            {
                firstPos = 0;
            }
            if (firstPos > 0)
            {
                //バイトレンジを指定する
                webreq.AddRange((int)firstPos);
                //If-Rangeヘッダを追加
                if (!string.IsNullOrEmpty(entityTag))
                {
                    webreq.Headers.Add("If-Range", entityTag);
                }
            }
            //そのほかのヘッダを指定する
            webreq.KeepAlive = false;
            webreq.Headers.Add("Pragma", "no-cache");
            webreq.Headers.Add("Cache-Control", "no-cache");

            System.Net.HttpWebResponse webres = null;

            try
            {
                //サーバーからの応答を受信するためのWebResponseを取得
                webres = (System.Net.HttpWebResponse)webreq.GetResponse();
            }
            catch (System.Net.WebException e)
            {
                //HTTPプロトコルエラーを捕捉し、内容を表示する
                if (e.Status == System.Net.WebExceptionStatus.ProtocolError)
                {
                    System.Net.HttpWebResponse errres =
                        (System.Net.HttpWebResponse)e.Response;
                    Console.WriteLine(errres.StatusCode);
                    Console.WriteLine(errres.StatusDescription);
                }
                else
                {
                    Console.WriteLine(e.Message);
                }

                webres.Close();
                throw new ApplicationException("データ取得エラー", e);
            }

            //エンティティタグの表示
            Console.WriteLine("ETag:" + webres.GetResponseHeader("ETag"));

            System.IO.Stream     strm = null;
            System.IO.FileStream fs   = null;
            try
            {
                //応答データを受信するためのStreamを取得
                strm = webres.GetResponseStream();

                //ファイルに書き込むためのFileStreamを作成
                fs = new System.IO.FileStream(downloadTempName,
                                              System.IO.FileMode.OpenOrCreate,
                                              System.IO.FileAccess.Write);

                //ファイルに書き込む位置を決定する
                //206Partial Contentステータスコードが返された時はContent-Rangeヘッダを調べる
                //それ以外のときは、先頭から書き込む
                long seekPos = 0;
                if (webres.StatusCode == System.Net.HttpStatusCode.PartialContent)
                {
                    string contentRange = webres.GetResponseHeader("Content-Range");
                    System.Text.RegularExpressions.Match m =
                        System.Text.RegularExpressions.Regex.Match(
                            contentRange,
                            @"bytes\s+(?:(?<first>\d*)-(?<last>\d*)|\*)/(?:(?<len>\d+)|\*)");
                    if (string.IsNullOrEmpty(m.Groups["first"].Value))
                    {
                        seekPos = 0;
                    }
                    else
                    {
                        seekPos = int.Parse(m.Groups["first"].Value);
                    }
                }
                else
                {
                    // すでにファイルがある場合にはファイルを削除
                    fs.Close();
                    fs.Dispose();
                    File.Delete(downloadTempName);
                    fs = new System.IO.FileStream(downloadTempName,
                                                  System.IO.FileMode.OpenOrCreate,
                                                  System.IO.FileAccess.Write);
                }
                // 途中からのダウンロードにあわせて 書き込み開始位置を変更する
                fs.SetLength(seekPos);
                fs.Position = seekPos;

                //応答データをファイルに書き込む
                byte[] readData       = new byte[1024 * 10];
                int    readSize       = 0;
                long   readDataLength = 0;
                for (; ;)
                {
                    readSize = strm.Read(readData, 0, readData.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                    fs.Write(readData, 0, readSize);
                    readDataLength += readSize;
                    this.InvokeDownloadStatus(url, readDataLength.ToString() + "/" + webres.ContentLength.ToString());
                }
            }

            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (strm != null)
                {
                    strm.Close();
                    strm.Dispose();
                }
                if (webres != null)
                {
                    webres.Close();
                }
            }
            // ダウンロードファイルの移動
            string bakFile = downloadFileFullName + ".bak";

            if (File.Exists(bakFile))
            {
                File.Delete(bakFile);
            }
            if (File.Exists(downloadFileFullName))
            {
                File.Move(downloadFileFullName, bakFile);
            }
            File.Move(downloadTempName, downloadFileFullName);

            this.InvokeDownloadStatus(url, "complate");

            WriteDownloadUrlLog(downloadToPath + "\\complate.log", url);
        }
Exemple #11
0
        private void ThreadableResumeDownload(string url, Action <int, int> stepCallback, Action errorCallback,
                                              Action successCallback)
        {
            //string tmpFullPath = TmpDownloadPath; //根据实际情况设置
            System.IO.FileStream downloadFileStream;
            //打开上次下载的文件或新建文件
            long lStartPos = 0;

            if (_useContinue && System.IO.File.Exists(TmpDownloadPath))
            {
                downloadFileStream = System.IO.File.OpenWrite(TmpDownloadPath);
                lStartPos          = downloadFileStream.Length;
                downloadFileStream.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针

                Console.WriteLine("Resume.... from {0}", lStartPos);
                //CDebug.LogConsole_MultiThread("Resume.... from {0}", lStartPos);
            }
            else
            {
                downloadFileStream = new System.IO.FileStream(TmpDownloadPath, System.IO.FileMode.OpenOrCreate);
                lStartPos          = 0;
            }
            System.Net.HttpWebRequest request = null;
            //打开网络连接
            try
            {
                request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos);  //设置Range值
                }
                Console.WriteLine("Getting Response : {0}", url);
                //CDebug.LogConsole_MultiThread("Getting Response : {0}", url);

                //向服务器请求,获得服务器回应数据流
                using (var response = request.GetResponse()) // TODO: Async Timeout
                {
                    TotalSize = (int)response.ContentLength;
                    //CDebug.LogConsole_MultiThread("Getted Response : {0}", url);
                    Console.WriteLine("Getted Response : {0}", url);
                    if (IsFinished)
                    {
                        throw new Exception(string.Format("Get Response ok, but is finished , maybe timeout! : {0}", url));
                    }
                    else
                    {
                        var totalSize = TotalSize;

                        using (var ns = response.GetResponseStream())
                        {
                            //CDebug.LogConsole_MultiThread("Start Stream: {0}", url);
                            Console.WriteLine("Start Stream: {0}", url);

                            int    downSize  = (int)lStartPos;
                            int    chunkSize = 10240;
                            byte[] nbytes    = new byte[chunkSize];
                            int    nReadSize = (int)lStartPos;
                            while ((nReadSize = ns.Read(nbytes, 0, chunkSize)) > 0)
                            {
                                if (IsFinished)
                                {
                                    throw new Exception("When Reading Web stream but Downloder Finished!");
                                }
                                downloadFileStream.Write(nbytes, 0, nReadSize);
                                downSize += nReadSize;
                                stepCallback(totalSize, downSize);
                            }
                            stepCallback(totalSize, totalSize);

                            request.Abort();
                            downloadFileStream.Close();
                        }
                    }
                }

                //CDebug.LogConsole_MultiThread("下载完成: {0}", url);
                Console.WriteLine("下载完成: {0}", url);

                if (File.Exists(_saveFullPath))
                {
                    File.Delete(_saveFullPath);
                }
                File.Move(TmpDownloadPath, _saveFullPath);
            }
            catch (Exception ex)
            {
                //CDebug.LogConsole_MultiThread("下载过程中出现错误:" + ex.ToString());
                Console.WriteLine("下载过程中出现错误:" + ex.ToString());

                downloadFileStream.Close();

                if (request != null)
                {
                    request.Abort();
                }

                try
                {
                    if (File.Exists(TmpDownloadPath))
                    {
                        File.Delete(TmpDownloadPath); // delete temporary file
                    }
                }
                catch (Exception e)
                {
                    //CDebug.LogConsole_MultiThread(e.Message);
                    Console.WriteLine(e.Message);
                }

                errorCallback();
            }
            successCallback();
        }
Exemple #12
0
        public void RequestWork(object state)
        {
            try
            {
#if NETFX_CORE
                System.Net.HttpWebRequest req = System.Net.HttpWebRequest.CreateHttp(new Uri(_Url));
#else
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
                System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(new Uri(_Url)) as System.Net.HttpWebRequest;
#else
                System.Net.HttpWebRequest req = new System.Net.HttpWebRequest(new Uri(_Url));
#endif
                req.KeepAlive = false;
#endif

                try
                {
                    lock (_CloseLock)
                    {
                        if (_Closed)
                        {
#if !HTTP_REQ_DONOT_ABORT
                            req.Abort();
#endif
                            if (_Status != RequestStatus.Finished)
                            {
                                _Error  = "Request Error (Cancelled)";
                                _Status = RequestStatus.Finished;
                            }
                            return;
                        }
                        _InnerReq = req;
                    }

#if !NETFX_CORE
                    req.Timeout          = int.MaxValue;
                    req.ReadWriteTimeout = int.MaxValue;
#if !HTTP_REQ_DONOT_ABORT
                    if (_Timeout > 0)
                    {
                        req.Timeout          = _Timeout;
                        req.ReadWriteTimeout = _Timeout;
                    }
#endif
#endif
                    if (_Headers != null)
                    {
                        foreach (var kvp in _Headers.Data)
                        {
                            var key = kvp.Key;
                            var val = (kvp.Value ?? "").ToString();
                            if (key.IndexOfAny(new[] { '\r', '\n', ':', }) >= 0)
                            {
                                continue; // it is dangerous, may be attacking.
                            }
                            if (val.IndexOfAny(new[] { '\r', '\n', }) >= 0)
                            {
                                continue; // it is dangerous, may be attacking.
                            }
                            else
                            {
                                req.Headers[key] = val;
                            }
                        }
                    }
                    if (_RangeEnabled)
                    {
                        long filepos = 0;
                        if (_Dest != null)
                        {
                            using (var stream = PlatExt.PlatDependant.OpenRead(_Dest))
                            {
                                if (stream != null)
                                {
                                    try
                                    {
                                        filepos = stream.Length;
                                    }
                                    catch (Exception e)
                                    {
                                        if (GLog.IsLogErrorEnabled)
                                        {
                                            GLog.LogException(e);
                                        }
                                    }
                                }
                            }
                        }
                        if (filepos <= 0)
                        {
                            if (_DestStream != null)
                            {
                                try
                                {
                                    if (_DestStream.CanSeek)
                                    {
                                        filepos = _DestStream.Length;
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (GLog.IsLogErrorEnabled)
                                    {
                                        GLog.LogException(e);
                                    }
                                }
                            }
                        }
                        if (filepos > 0)
                        {
                            if (filepos > int.MaxValue)
                            {
                                _RangeEnabled = false;
                            }
                            else
                            {
                                req.AddRange((int)filepos);
                            }
                        }
                        else
                        {
                            _RangeEnabled = false;
                        }
                    }
                    if (_Data != null && (_Data.Count > 0 || _Data.Encoded != null))
                    {
                        req.Method = "POST";
                        var data = _Data.Encoded;
                        if (data == null)
                        {
                            req.ContentType = _Data.ContentType;
                            data            = _Data.Encode();
                        }
                        else
                        {
                            req.ContentType = "application/octet-stream";
                        }

#if NETFX_CORE
                        var tstream = req.GetRequestStreamAsync();
                        if (_Timeout > 0)
                        {
                            if (!tstream.Wait(_Timeout))
                            {
                                throw new TimeoutException();
                            }
                        }
                        else
                        {
                            tstream.Wait();
                        }
                        var stream = tstream.Result;
#else
                        req.ContentLength = data.Length;
                        var stream = req.GetRequestStream();
#endif

                        lock (_CloseLock)
                        {
                            if (_Closed)
                            {
#if !HTTP_REQ_DONOT_ABORT
                                req.Abort();
#endif
                                if (_Status != RequestStatus.Finished)
                                {
                                    _Error  = "Request Error (Cancelled)";
                                    _Status = RequestStatus.Finished;
                                }
                                return;
                            }
                        }
                        if (stream != null)
                        {
#if NETFX_CORE
                            if (_Timeout > 0)
                            {
                                stream.WriteTimeout = _Timeout;
                            }
                            else
                            {
                                stream.WriteTimeout = int.MaxValue;
                            }
#endif

                            try
                            {
                                stream.Write(data, 0, data.Length);
                                stream.Flush();
                            }
                            finally
                            {
                                stream.Dispose();
                            }
                        }
                    }
                    else
                    {
                    }
                    lock (_CloseLock)
                    {
                        if (_Closed)
                        {
#if !HTTP_REQ_DONOT_ABORT
                            req.Abort();
#endif
                            if (_Status != RequestStatus.Finished)
                            {
                                _Error  = "Request Error (Cancelled)";
                                _Status = RequestStatus.Finished;
                            }
                            return;
                        }
                    }
#if NETFX_CORE
                    var tresp = req.GetResponseAsync();
                    if (_Timeout > 0)
                    {
                        if (!tresp.Wait(_Timeout))
                        {
                            throw new TimeoutException();
                        }
                    }
                    else
                    {
                        tresp.Wait();
                    }
                    var resp = tresp.Result;
#else
                    var resp = req.GetResponse();
#endif
                    lock (_CloseLock)
                    {
                        if (_Closed)
                        {
#if !HTTP_REQ_DONOT_ABORT
                            req.Abort();
#endif
                            if (_Status != RequestStatus.Finished)
                            {
                                _Error  = "Request Error (Cancelled)";
                                _Status = RequestStatus.Finished;
                            }
                            return;
                        }
                    }
                    if (resp != null)
                    {
                        try
                        {
                            _Total = (ulong)resp.ContentLength;
                        }
                        catch
                        {
                        }
                        try
                        {
                            _RespHeaders = new HttpRequestData();
                            foreach (var key in resp.Headers.AllKeys)
                            {
                                _RespHeaders.Add(key, resp.Headers[key]);
                            }

                            if (_RangeEnabled)
                            {
                                bool rangeRespFound = false;
                                foreach (var key in resp.Headers.AllKeys)
                                {
                                    if (key.ToLower() == "content-range")
                                    {
                                        rangeRespFound = true;
                                    }
                                }
                                if (!rangeRespFound)
                                {
                                    _RangeEnabled = false;
                                }
                            }

                            var stream = resp.GetResponseStream();
                            lock (_CloseLock)
                            {
                                if (_Closed)
                                {
#if !HTTP_REQ_DONOT_ABORT
                                    req.Abort();
#endif
                                    if (_Status != RequestStatus.Finished)
                                    {
                                        _Error  = "Request Error (Cancelled)";
                                        _Status = RequestStatus.Finished;
                                    }
                                    return;
                                }
                            }
                            if (stream != null)
                            {
#if NETFX_CORE
                                if (_Timeout > 0)
                                {
                                    stream.ReadTimeout = _Timeout;
                                }
                                else
                                {
                                    stream.ReadTimeout = int.MaxValue;
                                }
#endif
                                Stream streamd = null;
                                try
                                {
                                    byte[] buffer   = new byte[1024 * 1024];
                                    ulong  totalcnt = 0;
                                    int    readcnt  = 0;

                                    bool mem = false;
                                    if (_Dest != null)
                                    {
                                        if (_RangeEnabled)
                                        {
                                            streamd  = Capstones.PlatExt.PlatDependant.OpenAppend(_Dest);
                                            totalcnt = (ulong)streamd.Length;
                                        }
                                        else
                                        {
                                            streamd = Capstones.PlatExt.PlatDependant.OpenWrite(_Dest);
                                        }
#if HTTP_REQ_DONOT_ABORT
                                        if (streamd != null)
                                        {
                                            _CloseList.Add(streamd);
                                        }
#endif
                                    }
                                    if (streamd == null)
                                    {
                                        if (_DestStream != null)
                                        {
                                            if (_RangeEnabled)
                                            {
                                                _DestStream.Seek(0, SeekOrigin.End);
                                                totalcnt = (ulong)_DestStream.Length;
                                            }
                                            streamd = _DestStream;
                                        }
                                        else
                                        {
                                            mem     = true;
                                            streamd = new MemoryStream();
#if HTTP_REQ_DONOT_ABORT
                                            _CloseList.Add(streamd);
#endif
                                        }
                                    }

                                    if (_Total > 0)
                                    {
                                        _Total += totalcnt;
                                    }

                                    do
                                    {
                                        lock (_CloseLock)
                                        {
                                            if (_Closed)
                                            {
#if !HTTP_REQ_DONOT_ABORT
                                                req.Abort();
#endif
                                                if (_Status != RequestStatus.Finished)
                                                {
                                                    _Error  = "Request Error (Cancelled)";
                                                    _Status = RequestStatus.Finished;
                                                }
                                                return;
                                            }
                                        }
                                        try
                                        {
                                            readcnt = 0;
                                            readcnt = stream.Read(buffer, 0, 1024 * 1024);
                                            if (readcnt <= 0)
                                            {
                                                stream.ReadByte(); // when it is closed, we need read to raise exception.
                                                break;
                                            }

                                            streamd.Write(buffer, 0, readcnt);
                                            streamd.Flush();
                                        }
                                        catch (TimeoutException te)
                                        {
                                            if (GLog.IsLogErrorEnabled)
                                            {
                                                GLog.LogException(te);
                                            }
                                            _Error = "timedout";
                                        }
                                        catch (System.Net.WebException we)
                                        {
                                            if (GLog.IsLogErrorEnabled)
                                            {
                                                GLog.LogException(we);
                                            }
#if NETFX_CORE
                                            if (we.Status.ToString() == "Timeout")
#else
                                            if (we.Status == System.Net.WebExceptionStatus.Timeout)
#endif
                                            {
                                                _Error = "timedout";
                                            }
                                            else
                                            {
                                                _Error = "Request Error (Exception):\n" + we.ToString();
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            if (GLog.IsLogErrorEnabled)
                                            {
                                                GLog.LogException(e);
                                            }
                                            _Error = "Request Error (Exception):\n" + e.ToString();
                                        }
                                        lock (_CloseLock)
                                        {
                                            if (_Closed)
                                            {
#if !HTTP_REQ_DONOT_ABORT
                                                req.Abort();
#endif
                                                if (_Status != RequestStatus.Finished)
                                                {
                                                    _Error  = "Request Error (Cancelled)";
                                                    _Status = RequestStatus.Finished;
                                                }
                                                return;
                                            }
                                        }
                                        totalcnt += (ulong)readcnt;
                                        _Length   = totalcnt;
                                        //Capstones.PlatExt.PlatDependant.LogInfo(readcnt);
                                    } while (readcnt > 0);

                                    if (mem)
                                    {
                                        _Resp = ((MemoryStream)streamd).ToArray();
                                    }
                                }
                                finally
                                {
                                    stream.Dispose();
                                    if (streamd != null)
                                    {
                                        if (streamd != _DestStream)
                                        {
                                            streamd.Dispose();
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
#if NETFX_CORE
                            resp.Dispose();
#else
                            resp.Close();
#endif
                        }
                    }
                }
                catch (TimeoutException te)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(te);
                    }
                    _Error = "timedout";
                }
                catch (System.Net.WebException we)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(we);
                    }
#if NETFX_CORE
                    if (we.Status.ToString() == "Timeout")
#else
                    if (we.Status == System.Net.WebExceptionStatus.Timeout)
#endif
                    {
                        _Error = "timedout";
                    }
                    else
                    {
                        if (we.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)we.Response).StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable)
                        {
                        }
                        else
                        {
                            _Error = "Request Error (Exception):\n" + we.ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    _Error = "Request Error (Exception):\n" + e.ToString();
                }
                finally
                {
                    if (_Error == null)
                    {
                        lock (_CloseLock)
                        {
                            _Closed   = true;
                            _InnerReq = null;
                        }
                    }
                    else
                    {
                        StopRequest();
                    }
                }
            }
            catch (TimeoutException te)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(te);
                }
                _Error = "timedout";
            }
            catch (System.Net.WebException we)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(we);
                }
#if NETFX_CORE
                if (we.Status.ToString() == "Timeout")
#else
                if (we.Status == System.Net.WebExceptionStatus.Timeout)
#endif
                {
                    _Error = "timedout";
                }
                else
                {
                    _Error = "Request Error (Exception):\n" + we.ToString();
                }
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(e);
                }
                _Error = "Request Error (Exception):\n" + e.ToString();
            }
            finally
            {
                lock (_CloseLock)
                {
                    _Status = RequestStatus.Finished;
                    if (_OnDone != null)
                    {
                        var ondone = _OnDone;
                        _OnDone = null;
                        ondone();
                    }
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// 远程下载广告文件
        /// </summary>
        /// <param name="advertInfo"></param>
        /// <returns></returns>
        private bool DownAdvertFile(AdvertInfoModel advertInfo)
        {
            string strFileLocalPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "advert\\" + advertInfo.AdvListID + "\\" +
                                      advertInfo.FileName + "." + advertInfo.FileType;

            // 检测目录下是否有需要下载的正式文件
            if (System.IO.File.Exists(strFileLocalPath))
            {
                // 有正式的文件,无需下载
                return(true);
            }

            // 打开上次下载的文件或新建文件
            long lStartPos = 0;

            System.IO.FileStream fs;

            // 获取本地文件的存储位置目录以及文件名称(带文件格式)
            string strFileName = advertInfo.FileName;
            string strFilePath = advertInfo.FileName + "." + advertInfo.FileType;

            if ((string.IsNullOrEmpty(strFileName)) ||
                (string.IsNullOrEmpty(strFilePath)))
            {
                return(false);
            }

            // 生成下载临时文件
            string strFileTemp = strFileLocalPath + ".tmp";

            if (System.IO.File.Exists(strFileTemp))
            {
                fs        = System.IO.File.OpenWrite(strFileTemp);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
            }
            else
            {
                fs        = new System.IO.FileStream(strFileTemp, System.IO.FileMode.Create);
                lStartPos = 0;
            }

            //打开网络连接
            bool uploadResult = false;

            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(advertInfo.DownUrl);
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos); //设置Range值
                }

                //向服务器请求,获得服务器回应数据流
                System.IO.Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes    = new byte[1024];
                int    nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 1024);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize = ns.Read(nbytes, 0, 1024);
                }
                ns.Close();

                uploadResult = true;

                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                fs.Close();

                // 下载成功,把临时文件修改成正式文件
                if (uploadResult)
                {
                    Thread.Sleep(200);
                    try
                    {
                        if (System.IO.File.Exists(strFileTemp))
                        {
                            System.IO.File.Copy(strFileTemp, strFileLocalPath, true);
                            Thread.Sleep(200);
                            System.IO.File.Delete(strFileTemp);
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localFilePath"></param>
        /// <param name="url"></param>
        public int DownFile(string url, int threadCount)
        {
            autoEvent.WaitOne();  //阻塞当前线程,等待通知以继续执行
            //await LoadAsync(url,threadCount);


            string StrFileName = DownPath + name; //根据实际情况设置
            string StrUrl      = url;             //根据实际情况设置
            //打开上次下载的文件或新建文件
            long lStartPos = 0;

            if (System.IO.File.Exists(StrFileName))//另外如果文件已经下载完毕,就不需要再断点续传了,不然请求的range 会不合法会抛出异常。
            {
                fs        = System.IO.File.OpenWrite(StrFileName);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
            }
            else
            {
                fs        = new FileStream(StrFileName, System.IO.FileMode.Create);
                lStartPos = 0;
            }
            //打开网络连接
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos); //设置Range值
                }
                request.Timeout = 20000;
                System.Net.WebResponse response = request.GetResponse();
                //向服务器请求,获得服务器回应数据流
                ns = response.GetResponseStream();
                long   totalSize   = response.ContentLength;
                long   hasDownSize = 0;
                byte[] nbytes      = new byte[1024 * 2];//521,2048 etc
                int    nReadSize   = 0;
                nReadSize = ns.Read(nbytes, 0, nbytes.Length);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    downCount++;
                    nReadSize    = ns.Read(nbytes, 0, 1024 * 2);
                    hasDownSize += nReadSize;
                }
                fs.Close();
                ns.Close();
                response.Dispose();
                //CommonsCall.Compress(downStuep, StrFileName);
                CommonsCall.DeletePath(StrFileName);
                GC.Collect();
            }
            catch (ThreadAbortException e)
            {
                Thread.Sleep(10000);
                DownFile(url, threadCount);
            }
            catch (Exception ex)
            {
                Thread.Sleep(10000);
                DownFile(url, threadCount);
            }
            finally
            {
                threadCount--;
            }
            return(threadCount);
        }
Exemple #15
0
        //public DownloadFile(RichTextBox AgentLog)
        //{
        //    this.AgentLog = AgentLog;
        //}

        public void DownloadDoc()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            System.IO.FileStream fs;

            StrUrl      = doc.DownAddress;
            StrFileName = doc.StoreAddress + "\\" + doc.DocName + ".doc";
            bool IsFailed = true;

            #region

            try
            {
                if (System.IO.File.Exists(StrFileName))
                {
                    StrFileName = doc.StoreAddress + "\\" + doc.DocName + "(" + DateTime.Now.ToString("yyyyMMddhhmmss") + ").doc";
                    fs          = System.IO.File.OpenWrite(StrFileName);
                    lStartPos   = 0;//fs.Length;
                    fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
                    //移动文件流中的当前指针
                }
                else
                {
                    fs        = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
                    lStartPos = 0;
                }
            }
            catch (System.Exception ex)
            {
                lock (AgentLog)
                {
                    AgentLog.AppendText(StrFileName + "-------下载出错:" + ex.Message + "     " + string.Format("{0:G}", DateTime.Now) + "\n");
                }
                //MessageBox.Show(StrFileName + "-------下载出错:" + ex.Message);
                return;
            }
            #endregion
            #region
            //打开网络连接
            try
            {
                dt = DateTime.Now;
                lock (AgentLog)
                {
                    AgentLog.AppendText(StrFileName + "-------开始下载!   " + string.Format("{0:G}", dt) + "\n");
                }

                //测试
                //WriteLog log = new WriteLog();
                //log.WriteLogFile(Thread.CurrentThread.Name,0);

                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
                request.Method      = "GET";
                request.ContentType = "application/msword";
                long length = request.GetResponse().ContentLength;
                //lDownloadFile = length;
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos); //设置Range值
                }
                //向服务器请求,获得服务器回应数据流
                System.IO.Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes    = new byte[512];
                int    nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 512);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize   = ns.Read(nbytes, 0, 512);
                    lCurrentPos = fs.Length;
                }
                ns.Close();
                request.GetResponse().Close();
                dt = DateTime.Now;
                lock (AgentLog)
                {
                    AgentLog.AppendText(StrFileName + "-------下载完成!    " + string.Format("{0:G}", dt) + "\n");
                }
                baidu.downloadercount++;
            }
            catch (Exception ex)
            {
                lock (AgentLog)
                {
                    AgentLog.AppendText(StrFileName + "-------下载出错:" + ex.Message + "     " + string.Format("{0:G}", DateTime.Now) + "\n");
                }
                IsFailed = false;
                baidu.downfailcount++;
            }
            finally
            {
                fs.Close();
                //写入数据库
                doc.StoreAddress = StrFileName;
                doc.MD5          = md5_hash(StrFileName);
                doc.DocSize      = lCurrentPos;
                doc.DocType      = "doc";
                doc.StoreAddress = StrFileName;
                //doc.DocType = doc.DownAddress.Substring(doc.DownAddress.Length - 3, 3);

                if (AddData(IsFailed) == 1)
                {
                    lock (AgentLog)
                    {
                        AgentLog.AppendText(StrFileName + "-------下载信息导入完成!    " + string.Format("{0:G}", DateTime.Now) + "\n");
                    }
                }
                else
                {
                    lock (AgentLog)
                    {
                        AgentLog.AppendText(StrFileName + "-------下载信息导入失败!    " + string.Format("{0:G}", DateTime.Now) + "\n");
                    }
                }
            }
            #endregion
        }