当前位置: 首页>>代码示例>>C#>>正文


C# WebClient.DownloadFileTaskAsync方法代码示例

本文整理汇总了C#中System.Net.WebClient.DownloadFileTaskAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.DownloadFileTaskAsync方法的具体用法?C# WebClient.DownloadFileTaskAsync怎么用?C# WebClient.DownloadFileTaskAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


在下文中一共展示了WebClient.DownloadFileTaskAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: downloadFileAsync

        /// <summary>
        /// Downloads a file from the internet to a directory Asynchronously.
        /// </summary>
        /// <param name="URL">The URL of the file to download.</param>
        /// <param name="downloadDirectory">The directory to download the file to.</param>
        /// <param name="overwrite">Whether to overwrite what's there</param>
        /// <param name="errorActions">Actions to pass to showError on main error.</param>
        /// <param name="silent">Whether to show messages when it starts downloading or if the file allready existed</param>
        /// <param name="ignoreError">Whether to error if the main try loop fails.</param>
        /// <param name="specifyDownloadFile">Whether the downloadDirectory includes the file name to download to</param>
        public static async Task<bool> downloadFileAsync(string URL, string downloadDirectory, bool overwrite = false, bool silent = false, bool specifyDownloadFile = false, bool ignoreError = false, string[] errorActions = null)
        {

            //Get filename from URL
            string filename = Path.GetFileName(new Uri(URL).AbsolutePath);
            string dir = Path.GetDirectoryName(downloadDirectory);

            //If the file exists check if overwrite is accepted
            if (!(File.Exists(downloadDirectory + "/" + filename) | File.Exists(downloadDirectory)) || overwrite)
            {
                if (!specifyDownloadFile)
                {
                    //If the directory doesn't exist, create it
                    if (!Directory.Exists(downloadDirectory))
                    {
                        Logging.logMessage("Created directory " + downloadDirectory, 2);
                        Directory.CreateDirectory(downloadDirectory);
                    }
                }
                else
                {
                    //If the directory doesn't exist, create it
                    if (!Directory.Exists(dir))
                    {
                        Logging.logMessage("Created directory " + dir, 2);
                        Directory.CreateDirectory(dir);
                    }
                }

                //Acctually download file
                try
                {
                    if (!silent) Logging.logMessage("Trying to download " + URL + " to " + downloadDirectory, 2);
                    WebClient wc = new WebClient();
                    if (specifyDownloadFile)
                    {
                        await wc.DownloadFileTaskAsync(new Uri(URL), downloadDirectory);
                    }
                    else
                    {
                        await wc.DownloadFileTaskAsync(new Uri(URL), downloadDirectory + "/" + filename);
                    }
                    wc.Dispose();
                    wc = null;
                }
                catch (Exception e)
                {
                    if (!ignoreError) Logging.showError("Failed to download " + URL + " :" + e.ToString(), errorActions);
                    return false;
                }
            } else {
                if (!silent) Logging.logMessage("Didn't download " + URL + " to " + downloadDirectory + " because it already existed", 2);
            }
            return true;
        }
开发者ID:RX14,项目名称:RX-UTILS.NET,代码行数:65,代码来源:Web.cs

示例2: DownloadPhoto

        public static async Task DownloadPhoto(PhotoItem photo, String path, ProgressBar ProgressBar)
        {
            try
            {
                if (path[path.Length - 1] != '\\')
                {
                    path = path + "\\";
                }
                var fileName = photo.UrlPhoto;
                if (fileName.Length > 40)
                {
                    fileName = fileName.Substring(0, 40);
                }
                fileName = fileName.Replace(":", "").Replace("\\", "").Replace("/", "").Replace("*", "").Replace("?", "").Replace("\"", "");
                using (var client = new WebClient())
                {

                    client.DownloadProgressChanged += (o, args) =>
                    {
                        ProgressBar.Value = args.ProgressPercentage;
                    };
                    client.DownloadFileCompleted += (o, args) =>
                    {
                        ProgressBar.Value = 0;
                    };
                    await client.DownloadFileTaskAsync(new Uri(photo.UrlPhoto), path + fileName + ".jpg");
                }
            }
            catch (Exception)
            {
            }
        }
开发者ID:Konahrik,项目名称:KYM,代码行数:32,代码来源:Photos.cs

示例3: DownloadImage

 public async Task DownloadImage(string filePath, string url)
 {
     using (WebClient client = new WebClient())
     {
         await client.DownloadFileTaskAsync(url, filePath);
     }
 }
开发者ID:hamstercat,项目名称:perfect-media,代码行数:7,代码来源:FilesystemService.cs

示例4: DownloadList

        public void DownloadList(List<String> list, string pathToSave)
        {
            if (list.Count > 0)
            {

                foreach (string link in list)
                {
                    string FileName = link.Remove(0, link.LastIndexOf("/"));
                    WebClient wc = new WebClient();
                    wc.DownloadFileTaskAsync(new System.Uri(link), pathToSave + FileName);
                }

                DialogResult dialog = MessageBox.Show("Want to open folder with images?", "Done :D", MessageBoxButtons.YesNo);

                if (dialog == DialogResult.Yes)
                {
                    Process.Start("explorer.exe", pathToSave);
                }
                else
                {
                    return;
                }
            }
            else
            {
                MessageBox.Show("Found nothing _(._.)_");
            }
        }
开发者ID:andre1828,项目名称:SimpleWebScraper,代码行数:28,代码来源:Downloader.cs

示例5: DownloadAudio

        public static async Task DownloadAudio(AudioResponse composition, String path, ProgressBar ProgressBar)
        {
            try
            {
                if (path[path.Length - 1] != '\\')
                {
                    path = path + "\\";
                }
                var fileName = composition.Artist + " – " + composition.AudioTitle;
                if (fileName.Length > 40)
                {
                    fileName = fileName.Substring(0, 40);
                }
                fileName = fileName.Replace(":", "").Replace("\\", "").Replace("/", "").Replace("*", "").Replace("?", "").Replace("\"", "");
                using (var client = new WebClient())
                {

                    client.DownloadProgressChanged += (o, args) =>
                    {
                        ProgressBar.Value = args.ProgressPercentage;
                    };
                    client.DownloadFileCompleted += (o, args) =>
                    {
                        ProgressBar.Value = 0;
                    };
                    await client.DownloadFileTaskAsync(new Uri(composition.AudioUrl), path + fileName + ".mp3");
                }
            }
            catch (Exception)
            {
            }
        }
开发者ID:Konahrik,项目名称:KYM,代码行数:32,代码来源:Audio.cs

示例6: UpdateProductImage

        private void UpdateProductImage(Product product)
        {
            string imageUrl = product.ImagePath;

            if (!string.IsNullOrEmpty(imageUrl) && !VirtualPathUtility.IsAbsolute(imageUrl))
            {
                product.ImagePath = string.Format(
                                         "/Images/{0}{1}",
                                         product.ProductId,
                                         Path.GetExtension(imageUrl));

                this.RegisterAsyncTask(new PageAsyncTask(async (t) =>
                {
                    var startThread = Thread.CurrentThread.ManagedThreadId;

                    using (var wc = new WebClient())
                    {
                        await wc.DownloadFileTaskAsync(imageUrl, this.Server.MapPath(product.ImagePath));
                    }

                    var endThread = Thread.CurrentThread.ManagedThreadId;

                    this.threadsMessageLabel.Text = string.Format("Started on thread: {0}<br /> Finished on thread: {1}", startThread, endThread);
                }));
            }
        }
开发者ID:Microsoft-Web,项目名称:HOL-ASPNETWebForms,代码行数:26,代码来源:ProductDetails.aspx.cs

示例7: DownloadFiles

        internal async Task DownloadFiles(string downloadDir)
        {
            if (Directory.Exists(downloadDir))
                return;

            var list = new List<Task>();

            foreach (string fileName in AllFiles)
            {
                string url = string.Format(UrlFormat, Name, Version, fileName);
                var localFile = new FileInfo(Path.Combine(downloadDir, fileName));

                localFile.Directory.Create();

                using (WebClient client = new WebClient())
                {
                    var task = client.DownloadFileTaskAsync(url, localFile.FullName);
                    list.Add(task);
                }
            }

            OnDownloading(downloadDir);
            await Task.WhenAll(list);
            OnDownloaded(downloadDir);
        }
开发者ID:gep13,项目名称:Packman,代码行数:25,代码来源:InstallablePackage.cs

示例8: Download

        public void Download(Uri downloadLink, Action<String> callback)
        {
            WebClient client = new WebClient();

            var fileName = Path.GetFileName(downloadLink.AbsoluteUri);
            var filePath = Path.Combine(_downloadLocation, fileName);

            Console.WriteLine("Downloading {0}..." , downloadLink);
            client.DownloadProgressChanged += (s, e) =>
            {
                Console.Write("\r{0}%", e.ProgressPercentage);
            };

            client.DownloadFileCompleted += (s, e) =>
            {
                Console.WriteLine();
                Console.WriteLine("Downloaded.");
                //Thread.Yield(); // useless
                callback(filePath);
            };

            // awesomeness ;)
            client.DownloadFileTaskAsync(downloadLink, filePath)
                .Wait();
        }
开发者ID:ZainShaikh,项目名称:NodeInstaller,代码行数:25,代码来源:Downloader.cs

示例9: DownloadFile

 public static void DownloadFile(LeafNodeProgress progress, String url, String path)
 {
     var tempFileInfo = new FileInfo(Path.Combine(FolderUtils.SystemTempFolder.FullName, Guid.NewGuid().ToString("N")));
     var targetFileInfo = new FileInfo(path);
     using (var client = new WebClient())
     {
         client.DownloadProgressChanged += (i, o) =>
         {
             progress.Percent = o.ProgressPercentage;
         };
         try
         {
             client.DownloadFileTaskAsync(url, tempFileInfo.FullName).Wait();
         }
         catch (AggregateException ex)
         {
             throw ex.GetBaseException();
         }
         if (targetFileInfo.Directory != null && !targetFileInfo.Directory.Exists)
         {
             targetFileInfo.Directory.Create();
         }
         File.Copy(tempFileInfo.FullName, targetFileInfo.FullName, true);
     }
 }
开发者ID:cybcaoyibo,项目名称:TerminologyLauncher,代码行数:25,代码来源:DownloadUtils.cs

示例10: DownloadFiles

        List<Task> DownloadFiles(string downloadDir, IEnumerable<string> files)
        {
            var list = new List<Task>();

            foreach (string fileName in files)
            {
                try
                {
                    string url = string.Format(UrlFormat, Name, Version, fileName);
                    var localFile = new FileInfo(Path.Combine(downloadDir, fileName));

                    localFile.Directory.Create();

                    using (WebClient client = new WebClient())
                    {
                        var task = client.DownloadFileTaskAsync(url, localFile.FullName);
                        list.Add(task);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Write(ex);
                }
            }

            return list;
        }
开发者ID:yannduran,项目名称:Packman,代码行数:27,代码来源:InstallablePackage.cs

示例11: DownloadFile

 public async Task DownloadFile()
 {
     if (!IsDownloading && (ShowDownloadNow || ShowUpdateNow))
     {
         IsDownloading = true;
         try
         {
             WebClient client = new WebClient();
             await client.DownloadFileTaskAsync(DownloadFrom, SaveFileTo + ".tmp");
             File.Delete(SaveFileTo);
             File.Move(SaveFileTo + ".tmp", SaveFileTo);
             File.SetCreationTime(SaveFileTo, LastChangedOn);
             IsDownloading = false;
             UpdateCommandBools();
         }
         catch (Exception ex)
         {
             IsDownloading = false;
             MessageBox.Show(ex.ToString(), "error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
             if (File.Exists(SaveFileTo + ".tmp"))
             {
                 try
                 {
                     File.Delete(SaveFileTo + ".tmp");
                 }
                 catch
                 { }
             }
         }
     }
 }
开发者ID:Gordon-Beeming,项目名称:Sys-Internals-Updater,代码行数:31,代码来源:SysInternalFile.cs

示例12: Download

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName">Path where to download Setup.exe</param>
        /// <returns></returns>
        /// <exception cref="LogazmicIntegrationException"></exception>
        public async Task Download(string fileName)
        {
            string latestReleaseUrl;
            try
            {
                latestReleaseUrl = (await GetLatestReleaseUrl())?.ToString();
            }
            catch (Exception e)
            {
                throw new LogazmicIntegrationException("Failed to get latest release url", e);
            }
            
            if (string.IsNullOrEmpty(latestReleaseUrl))
                throw new LogazmicIntegrationException("Failed to get latest release url. It was null");

            try
            {
                var downloadUrl = ConvertUrl(latestReleaseUrl);
                using (var client = new WebClient())
                {
                    if (WebProxy != null)
                    {
                        client.Proxy = WebProxy;
                    }

                    await client.DownloadFileTaskAsync(downloadUrl, fileName);
                }
            }
            catch (Exception e)
            {
                throw new LogazmicIntegrationException("Failed to download Setup.exe", e);
            }
        }
开发者ID:mikel785,项目名称:Logazmic,代码行数:39,代码来源:Downloader.cs

示例13: DownloadFileAsync

 /// <summary>
 /// Use a <see cref="WebClient"/> to asynchronously download a file and update the console 
 /// every time another percent completes.
 /// </summary>
 /// <param name="lecture"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 private async Task DownloadFileAsync(LectureInfo lecture, int id)
 {
     using (WebClient wc = new WebClient())
     {
         wc.DownloadProgressChanged += (sender, e) => UpdateConsole(e.ProgressPercentage, lecture, id);
         await wc.DownloadFileTaskAsync(lecture.Url, lecture.FileNameMP4);
     }
 }
开发者ID:tompostler,项目名称:lecture-convert,代码行数:15,代码来源:Download.cs

示例14: DownloadReleaseZip

 static async Task DownloadReleaseZip(Action<int> progress, string downloadFilePath, string releaseDownloadUrl)
 {
     using (var webClient = new WebClient())
     {
         webClient.DownloadProgressChanged += (s, ee) => progress(ee.ProgressPercentage);
         await webClient.DownloadFileTaskAsync(new Uri(releaseDownloadUrl), downloadFilePath);
     }
 }
开发者ID:vipoo,项目名称:iRacingApplicationVersionManager,代码行数:8,代码来源:ReleaseInstaller.cs

示例15: Start

 public void Start()
 {
     using (var client = new WebClient())
     {
         client.Proxy = Utilities.GetProxyWithCredentials();
         client.DownloadProgressChanged += client_DownloadProgressChanged;
         client.DownloadFileTaskAsync(URL, Path).Wait();
     }
 }
开发者ID:rajeshwarn,项目名称:VideoDownloader,代码行数:9,代码来源:DownloadHandler.cs


注:本文中的System.Net.WebClient.DownloadFileTaskAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。