示例#1
0
        public static void FileReplace(string filePathSrc, string filePathDest, bool bMove = true)
        {
            // Move/Copy and silently replace any file if it exists.
            // Assume Dir for filePathDest exists.

            if (filePathSrc == filePathDest)
            {
                return;
            }
            if (!DirUtil.DirCreateForFile(filePathDest))
            {
                FileDelete(filePathDest);
            }
            if (bMove)
            {
                System.IO.File.Move(filePathSrc, filePathDest);
            }
            else
            {
                System.IO.File.Copy(filePathSrc, filePathDest, true);
            }
        }
示例#2
0
        public void DownloadFileRaw(bool allowRedirect = false)
        {
            // Synchronous get file. Doesn't call any events. no protection from throw.
            // https://github.com/aspnet/LibraryManager/blob/master/src/LibraryManager/CacheService/WebRequestHandler.cs

            DirUtil.DirCreateForFile(DestPath);

            if (!allowRedirect)
            {
                using (var wc = new WebClient())
                {
                    wc.DownloadFile(SrcURL, DestPath);  // vs DownloadData()
                }
            }
            else
            {
                // Make sure we allow redirects and such.
                // TODO convert to use HttpClient
                // https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-request-data-using-the-webrequest-class

                var            req  = WebRequest.Create(SrcURL);
                HttpWebRequest reqH = ((HttpWebRequest)req);

                // reqH.AuthenticationLevel = AuthenticationLevel.None;
                // reqH.AllowAutoRedirect = true;
                reqH.KeepAlive = false;
                reqH.Proxy     = null;  // makes it slow.
                                        // reqH.ServicePoint.ConnectionLeaseTimeout = 0;
                                        // reqH.ReadWriteTimeout = System.Threading.Timeout.Infinite;
                reqH.ServicePoint.Expect100Continue = false;
                reqH.ProtocolVersion = HttpVersion.Version10;

                reqH.Credentials           = CredentialCache.DefaultCredentials;
                reqH.UseDefaultCredentials = true;
                reqH.Date = TimeNow.Utc;

                // reqH.Timeout = 5000;67
                reqH.Method = "GET";
                reqH.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0, no-cache, no-store");

                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                //var cookieJar = new CookieContainer();
                //reqH.CookieContainer = cookieJar;

                // Pretend to be a browser.
                reqH.UserAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0";
                // reqH.Accept = "*/*";
                // reqH.Headers.Add("Accept-Encoding: gzip, deflate");
                // reqH.Headers.Add("Accept-Language: en-US");

                // Send the 'WebRequest' and wait for response.
                // WebRequest HttpWebRequest timeout timed out at Associating Connection
                using (var rsp = req.GetResponse())
                {
                    using (var dst = File.Create(DestPath))
                    {
                        rsp.GetResponseStream().CopyTo(dst);
                    }
                    rsp.Close();
                }
            }
        }
示例#3
0
        public async Task DownloadFileAsync(HttpClient client)
        {
            // Get some HTTP/HTTPS URL and put in local file.
            // can throw.

            DirUtil.DirCreateForFile(DestPath);

            HttpResponseMessage response = await client.GetAsync(SrcURL);

            response.EnsureSuccessStatusCode();

            using (var dst = File.Create(DestPath))     // open/create local destination file.
            {
                if (ProgressEvent == null)
                {
                    // No progress events
                    await response.Content.CopyToAsync(dst);
                }
                else
                {
                    // Send progress events.

                    DateTime  lastEvent   = DateTime.Now;                           // measure relative time.
                    const int kBlockSize  = 8192;
                    long?     totalBytes1 = response.Content.Headers.ContentLength; // may not be known/sent.
                    bool      isEstimated = totalBytes1 == null;                    // we dont know the total size ?
                    long      totalBytes  = totalBytes1 ?? kBlockSize;

                    using (Stream contentStream = await response.Content.ReadAsStreamAsync())
                    {
                        long currentBytesRead = 0L;
                        var  buffer           = new byte[kBlockSize];

                        while (true)
                        {
                            if (currentBytesRead > totalBytes)
                            {
                                isEstimated = true;
                                totalBytes += kBlockSize;       // re-estimated total.
                            }

                            int bytesRead = await contentStream.ReadAsync(buffer, 0, kBlockSize);

                            if (bytesRead == 0)
                            {
                                ProgressEvent(currentBytesRead, isEstimated ? currentBytesRead : totalBytes);
                                break;  // we are done!
                            }

                            await dst.WriteAsync(buffer, 0, bytesRead);

                            currentBytesRead += bytesRead;

                            DateTime tLocalNow = DateTime.Now;
                            TimeSpan elapsed   = tLocalNow - lastEvent;
                            if (elapsed.TotalSeconds > 0.50)
                            {
                                ProgressEvent(currentBytesRead, totalBytes);
                                lastEvent = tLocalNow;
                            }
                        }
                    }
                }
            }
        }
示例#4
0
 public static bool DirCreateForFile(string filePath)
 {
     // I'm about to open a file for writing.
     return(DirUtil.DirCreate(Path.GetDirectoryName(filePath)));
 }