コード例 #1
0
 /// <summary>
 /// Http方式下载文件
 /// </summary>
 /// <param name="url">http地址</param>
 /// <param name="localfile">本地文件</param>
 /// <returns></returns>
 public bool DownloadFile()
 {
     init();
     if (CurrPostion == FileInfo.FileSize)
     {
         //已经下载完成
         DownloadFileOk();
         return(true);
     }
     using (Stream writeStream = File.OpenWrite(LocalfileWithSuffix)) {
         using (Stream readStream = response.GetResponseStream())
         {
             byte[] btArray     = new byte[BufferSize];
             int    contentSize = 0;
             while ((contentSize = readStream.Read(btArray, 0, btArray.Length)) > 0)
             {
                 writeStream.Write(btArray, 0, contentSize);
                 CurrPostion += contentSize;
                 //通知进度
                 DownloadPercent?.Invoke(LocalfileReal, LocalfileWithSuffix, (int)(CurrPostion * 100 / FileInfo.FileSize));
             }
         }
     }
     DownloadFileOk();
     return(true);
 }
コード例 #2
0
ファイル: WebClient.cs プロジェクト: landunin/meta-core
        public virtual bool DownloadFile(string fileName, string url, DownloadPercent callback)
        {
            Func <bool> action = () => DownloadFileAppropriately(fileName, url, callback);

            try
            {
                var result = action.BeginInvoke(null, null);
                return(action.EndInvoke(result));
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }
コード例 #3
0
        void DownloadFile(string filePathLocal, string path, DownloadPercent percent)
        {
            string filePath = filePathLocal.Substring(0, filePathLocal.LastIndexOf('\\') + 1);

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            FileStream outputStream = new FileStream(filePathLocal, FileMode.Create);

            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ServerIP + path.Replace("/", "//")));

            reqFTP.Credentials = new NetworkCredential(_UserName, _PassWord);
            reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary   = true;
            reqFTP.UsePassive  = false;

            FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
            Stream         ftpStream = response.GetResponseStream();

            long cl = GetFileSize(path);
            long totalDownloadedByte = 0;
            int  bufferSize          = 1024;
            int  readCount;

            byte[] buffer = new byte[bufferSize];

            readCount = ftpStream.Read(buffer, 0, bufferSize);

            while (readCount > 0)
            {
                totalDownloadedByte = readCount + totalDownloadedByte;
                outputStream.Write(buffer, 0, readCount);

                float fl = (float)totalDownloadedByte / (float)cl * 100;

                if (percent != null)
                {
                    percent(fl);
                }

                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }

            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }
コード例 #4
0
        internal bool DownloadFileFromSwift(string zipFile, string clientDownloadUrl, DownloadPercent callback)
        {
            Login();
            string cleanClientDownloadUrl = clientDownloadUrl;
            if (clientDownloadUrl.Contains("temp_url_sig"))
            {
                cleanClientDownloadUrl = clientDownloadUrl.Substring(0, clientDownloadUrl.IndexOf("temp_url_sig")) + "[redacted]";
            }
            Trace.TraceInformation("Downloading artifacts from {0} to {1}", cleanClientDownloadUrl, zipFile);

            try
            {
                try
                {
                    string status = "connecting";

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(clientDownloadUrl);
                    HttpWebResponse response = null;
                    request.Timeout = Jenkins.HTTP_WEB_REQUEST_TIMEOUT_BASE;
                    // webRequest.ReadWriteTimeout = Jenkins.HTTP_WEB_REQUEST_TIMEOUT_BASE;
                    request.KeepAlive = false;
                    request.CookieContainer = this.AuthCookies;

                    FileStream output = new FileStream(zipFile, FileMode.Append, FileAccess.Write);
                    // test resume download:
                    //  output.Seek(0, SeekOrigin.Begin);
                    //  output.Write(new byte[] { (byte)'P', (byte)'K', 3, 4 }, 0, 4);
                    using (output)
                    using (request as IDisposable)
                    {
                        long BytesRead = output.Position;
                        if (BytesRead > 0)
                        {
                            request.AddRange(BytesRead);
                        }

                        try
                        {
                            response = (HttpWebResponse)request.GetResponse();
                            //create network stream
                            var ns = response.GetResponseStream();
                            var acceptRanges = String.Compare(response.Headers["Accept-Ranges"], "bytes", true) == 0;
                            if (acceptRanges == false)
                            {
                                output.Seek(0, SeekOrigin.Begin);
                                BytesRead = 0;
                            }
                            byte[] buffer = new byte[8 * 1024];
                            while (true)
                            {
                                var res = ns.BeginRead(buffer, 0, buffer.Length, null, null);
                                bool readSucceeded = res.AsyncWaitHandle.WaitOne(Jenkins.HTTP_WEB_REQUEST_TIMEOUT_BASE);
                                if (readSucceeded == false)
                                {
                                    throw new WebException(String.Format("Connection timed out {0}", status));
                                }
                                int bytesRead = ns.EndRead(res);
                                if (bytesRead == 0)
                                    break;
                                output.Write(buffer, 0, bytesRead);
                                int percentProgress = (int)(((double)output.Position) / (BytesRead + response.ContentLength) * 99.0);
                                status = String.Format("at {0}%", percentProgress);
                                callback(percentProgress);
                            }
                        }
                        catch (WebException e)
                        {
                            IDisposable disp = e.Response as IDisposable;
                            if (disp != null)
                                disp.Dispose();
                            throw;
                        }
                        callback(100);
                    }
                    Trace.TraceInformation("Download from S3 succeeded {0}", zipFile);
                    return true;
                }
                catch (System.Reflection.TargetInvocationException ex)
                {
                    // FIXME: I don't think this is reachable anymore
                    throw ex.InnerException;
                }

            }
            catch (WebException ex)
            {
                Trace.TraceError(String.Format("Error downloading {0}. Exception follows", cleanClientDownloadUrl));
                Trace.TraceError(ex.ToString());
            }
            return false;
        }
コード例 #5
0
        /// <summary>
        /// 程序下载
        /// </summary>
        /// <param name="modelCode">车型代码</param>
        /// <param name="status">软件版本状态</param>
        /// <param name="percent">下载进度</param>
        /// <returns>成功返回TRUE, 失败返回False</returns>
        public bool DownloadFile(string modelCode, VersionStatus status, DownloadPercent percent)
        {
            try
            {
                if (modelCode == null || status == VersionStatus.Null)
                {
                    throw new Exception("参数值无效");
                }

                string currerntFilePath = System.Environment.CurrentDirectory + "\\TCU程序\\" + modelCode + "\\" + status.ToString() + "\\";

                if (!Directory.Exists(currerntFilePath))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(currerntFilePath);
                    directoryInfo.Create();
                }

                System.IO.DirectoryInfo dir = new DirectoryInfo(currerntFilePath);
                bool isDownload             = false;

                if (dir.GetFiles().Length == 0)
                {
                    isDownload = true;
                }
                else
                {
                    List <FileInfo> lstFile = dir.GetFiles().Where(k => k.Name.Contains("TCU程序")).ToList();

                    if (lstFile.Count() == 0)
                    {
                        isDownload = true;
                    }
                    else
                    {
                        string fileName = lstFile[0].Name;

                        DataTable tempTable = GetSoftWareInfo(modelCode, status);

                        if (tempTable == null || tempTable.Rows.Count == 0)
                        {
                            throw new Exception("无法获得文件信息");
                        }

                        fileName = fileName.Substring(fileName.IndexOf("(") + 1, fileName.IndexOf(")") - fileName.IndexOf("(") - 1);
                        string version = tempTable.Rows[0]["Version"].ToString();

                        if (string.Compare(version, fileName) > 0)
                        {
                            isDownload = true;
                        }
                    }
                }

                if (isDownload)
                {
                    foreach (FileInfo fi in dir.GetFiles())
                    {
                        fi.Delete();
                    }

                    Download_TxtFile(modelCode, status, currerntFilePath);
                    Download_SoftFile(modelCode, status, currerntFilePath, percent);
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #6
0
        void Download_SoftFile(string modelCode, VersionStatus status, string filePathLocal, DownloadPercent percent)
        {
            try
            {
                DataTable infoTable = GetSoftWareInfo(modelCode, status);

                if (infoTable == null || infoTable.Rows.Count == 0)
                {
                    throw new Exception("未查询到相关信息");
                }

                string versionTxt = "";

                if (infoTable.Rows[0]["Version"].ToString().Trim().Length > 10)
                {
                    versionTxt = infoTable.Rows[0]["Version"].ToString().Trim().Substring(0, infoTable.Rows[0]["Version"].ToString().Trim().Length - 1) + ")"
                                 + infoTable.Rows[0]["Version"].ToString().Trim().Substring(infoTable.Rows[0]["Version"].ToString().Trim().Length - 1);
                }
                else
                {
                    versionTxt = infoTable.Rows[0]["Version"].ToString().Trim() + ")";
                }

                DownloadFile(filePathLocal
                             + "TCU程序(" + versionTxt + infoTable.Rows[0]["FileType"].ToString(),
                             infoTable.Rows[0]["FilePath"].ToString(), percent);

                DownloadFile(filePathLocal
                             + infoTable.Rows[0]["DLLName"].ToString()
                             + infoTable.Rows[0]["DLLFileType"].ToString(),
                             infoTable.Rows[0]["DLLFilePath"].ToString(), percent);
            }
            catch (Exception exec)
            {
                throw new Exception(string.Format("异常位置: {0}, 详细信息: {1}", exec.StackTrace, exec.Message));
            }
        }
コード例 #7
0
ファイル: WebClient.cs プロジェクト: landunin/meta-core
        public virtual bool DownloadFileAppropriately(string fileName, string url, DownloadPercent callback)
        {
            string fullUrl = this.GetFullUrl(url);

            Trace.TraceInformation("Downloading artifacts from {0} to {1}", fullUrl, fileName);

            int    maxProgress     = 0;
            object maxProgressLock = new object();

            try
            {
                string status = "Connecting ...";
                using (CookieAwareWebClient webClient = new CookieAwareWebClient())
                {
                    webClient.AuthCookies = this.AuthCookies;
                    webClient.Timeout     = this.HTTP_WEB_REQUEST_TIMEOUT;
                    //webClient.AllowReadStreamBuffering = false;

                    Semaphore progress      = new Semaphore(0, int.MaxValue);
                    Semaphore completed     = new Semaphore(0, 1);
                    Exception downloadError = null;
                    webClient.DownloadFileCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
                    {
                        downloadError = e.Error;
                        completed.Release();
                    };
                    webClient.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e)
                    {
                        lock (maxProgressLock)
                        {
                            int percentProgress = (int)(((double)e.BytesReceived / e.TotalBytesToReceive) * 99.0);
                            if (percentProgress > maxProgress)
                            {
                                // e.ProgressPercentage is not correct, as (almost) all the time is spent uploading
                                maxProgress = percentProgress;
                                callback(maxProgress);
                                status = String.Format("at {0}%", percentProgress);
                            }
                        }
                        progress.Release();
                    };

                    webClient.DownloadFileAsync(new Uri(fullUrl), fileName);

                    while (true)
                    {
                        WaitHandle[] handles = new WaitHandle[] { completed, progress };
                        int          timeout = webClient.Timeout;
                        lock (maxProgressLock)
                        {
                            // Workaround for Fiddler proxy: Fiddler downloads all the data at once, then passes it on to clients
                            if (maxProgress < 2)
                            {
                                handles = new WaitHandle[] { completed };
                                timeout = this.HTTP_WEB_REQUEST_ASYNC_TIMEOUT;
                            }
                        }
                        int handle = WaitHandle.WaitAny(handles, timeout);
                        if (handle == 0)
                        {
                            lock (maxProgressLock)
                            {
                                maxProgress = 100;
                                callback(maxProgress);
                            }
                            break;
                        }
                        if (handle == System.Threading.WaitHandle.WaitTimeout)
                        {
                            webClient.CancelAsync();
                            throw new WebException(String.Format("Connection timed out {0}", status));
                        }
                        if (handle != 1)
                        {
                            //TODO: Kevin, please specify the failure condition. Not clear what state we are in.
                            throw new WebException();
                        }
                    }
                    if (downloadError != null)
                    {
                        throw downloadError;
                    }

                    Trace.TraceInformation("Download from {0} succeeded {1}", fullUrl, fileName);
                    return(true);
                }
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }
コード例 #8
0
ファイル: Jenkins.cs プロジェクト: landunin/meta-core
        internal bool DownloadFileFromSwift(string zipFile, string clientDownloadUrl, DownloadPercent callback)
        {
            Login();
            string cleanClientDownloadUrl = clientDownloadUrl;

            if (clientDownloadUrl.Contains("temp_url_sig"))
            {
                cleanClientDownloadUrl = clientDownloadUrl.Substring(0, clientDownloadUrl.IndexOf("temp_url_sig")) + "[redacted]";
            }
            Trace.TraceInformation("Downloading artifacts from {0} to {1}", cleanClientDownloadUrl, zipFile);

            try
            {
                try
                {
                    string status = "connecting";

                    HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(clientDownloadUrl);
                    HttpWebResponse response = null;
                    request.Timeout = Jenkins.HTTP_WEB_REQUEST_TIMEOUT_BASE;
                    // webRequest.ReadWriteTimeout = Jenkins.HTTP_WEB_REQUEST_TIMEOUT_BASE;
                    request.KeepAlive       = false;
                    request.CookieContainer = this.AuthCookies;

                    FileStream output = new FileStream(zipFile, FileMode.Append, FileAccess.Write);
                    // test resume download:
                    //  output.Seek(0, SeekOrigin.Begin);
                    //  output.Write(new byte[] { (byte)'P', (byte)'K', 3, 4 }, 0, 4);
                    using (output)
                        using (request as IDisposable)
                        {
                            long BytesRead = output.Position;
                            if (BytesRead > 0)
                            {
                                request.AddRange(BytesRead);
                            }

                            try
                            {
                                response = (HttpWebResponse)request.GetResponse();
                                //create network stream
                                var ns           = response.GetResponseStream();
                                var acceptRanges = String.Compare(response.Headers["Accept-Ranges"], "bytes", true) == 0;
                                if (acceptRanges == false)
                                {
                                    output.Seek(0, SeekOrigin.Begin);
                                    BytesRead = 0;
                                }
                                byte[] buffer = new byte[8 * 1024];
                                while (true)
                                {
                                    var  res           = ns.BeginRead(buffer, 0, buffer.Length, null, null);
                                    bool readSucceeded = res.AsyncWaitHandle.WaitOne(Jenkins.HTTP_WEB_REQUEST_TIMEOUT_BASE);
                                    if (readSucceeded == false)
                                    {
                                        throw new WebException(String.Format("Connection timed out {0}", status));
                                    }
                                    int bytesRead = ns.EndRead(res);
                                    if (bytesRead == 0)
                                    {
                                        break;
                                    }
                                    output.Write(buffer, 0, bytesRead);
                                    int percentProgress = (int)(((double)output.Position) / (BytesRead + response.ContentLength) * 99.0);
                                    status = String.Format("at {0}%", percentProgress);
                                    callback(percentProgress);
                                }
                            }
                            catch (WebException e)
                            {
                                IDisposable disp = e.Response as IDisposable;
                                if (disp != null)
                                {
                                    disp.Dispose();
                                }
                                throw;
                            }
                            callback(100);
                        }
                    Trace.TraceInformation("Download from S3 succeeded {0}", zipFile);
                    return(true);
                }
                catch (System.Reflection.TargetInvocationException ex)
                {
                    // FIXME: I don't think this is reachable anymore
                    throw ex.InnerException;
                }
            }
            catch (WebException ex)
            {
                Trace.TraceError(String.Format("Error downloading {0}. Exception follows", cleanClientDownloadUrl));
                Trace.TraceError(ex.ToString());
            }
            return(false);
        }