CASCExplorer.SyncDownloader.DownloadFile C# (CSharp) Method

DownloadFile() public method

public DownloadFile ( string url, string path ) : void
url string
path string
return void
        public void DownloadFile(string url, string path)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));

            //using (var client = new HttpClient())
            //{
            //    var msg = client.GetAsync(url).Result;

            //    using (Stream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            //    {
            //        //CacheMetaData.AddToCache(resp, path);
            //        //CopyToStream(stream, fs, resp.ContentLength);

            //        msg.Content.CopyToAsync(fs).Wait();
            //    }
            //}

            HttpWebRequest request = WebRequest.CreateHttp(url);

            using (HttpWebResponse resp = (HttpWebResponse)request.GetResponseAsync().Result)
            using (Stream stream = resp.GetResponseStream())
            using (Stream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                //CacheMetaData.AddToCache(resp, path);
                CopyToStream(stream, fs, resp.ContentLength);
            }
        }

Usage Example

Example #1
0
        public Stream OpenFile(string name, string url, bool isData)
        {
            if (!Enabled)
            {
                return(null);
            }

            if (isData && !CacheData)
            {
                return(null);
            }

            string file = Path.Combine(_cachePath, name);

            Logger.WriteLine("CDNCache: Opening file {0}", file);

            FileInfo fi = new FileInfo(file);

            if (!fi.Exists)
            {
                _downloader.DownloadFile(url, file);
            }

            if (Validate)
            {
                CacheMetaData meta = CacheMetaData.Load(file) ?? _downloader.GetMetaData(url, file);

                if (meta == null)
                {
                    throw new Exception(string.Format("unable to validate file {0}", file));
                }

                bool sizeOk, md5Ok;

                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    sizeOk = fs.Length == meta.Size;
                    md5Ok  = _md5.ComputeHash(fs).EqualsTo(meta.MD5);
                }

                if (!sizeOk || !md5Ok)
                {
                    _downloader.DownloadFile(url, file);
                }
            }

            return(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
        }