本文整理汇总了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;
}
示例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)
{
}
}
示例3: DownloadImage
public async Task DownloadImage(string filePath, string url)
{
using (WebClient client = new WebClient())
{
await client.DownloadFileTaskAsync(url, filePath);
}
}
示例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 _(._.)_");
}
}
示例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)
{
}
}
示例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);
}));
}
}
示例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);
}
示例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();
}
示例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);
}
}
示例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;
}
示例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
{ }
}
}
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例15: Start
public void Start()
{
using (var client = new WebClient())
{
client.Proxy = Utilities.GetProxyWithCredentials();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileTaskAsync(URL, Path).Wait();
}
}