本文整理汇总了C#中WebClient.DownloadFileAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.DownloadFileAsync方法的具体用法?C# WebClient.DownloadFileAsync怎么用?C# WebClient.DownloadFileAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类WebClient
的用法示例。
在下文中一共展示了WebClient.DownloadFileAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnButton1Clicked
protected void OnButton1Clicked(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty (entry1.Text)) {
// Our test youtube link
string link = entry1.Text;
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls (link);
if (vid == true) {
VideoInfo video = videoInfos
.First (info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);
WebClient wc = new WebClient ();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync (new Uri (video.DownloadUrl), Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + @"/" + video.Title + video.VideoExtension);
label1.Text = dlspeed;
}
else {
VideoInfo video = videoInfos
.Where(info => info.CanExtractAudio)
.OrderByDescending(info => info.AudioBitrate)
.First();
entry1.Text = video.DownloadUrl;
/*WebClient wc = new WebClient ();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync (new Uri (video.DownloadUrl), Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + @"/" + video.Title + video.AudioExtension);
*/}
}
}
示例2: Main
static void Main()
{
while (true)
{
try
{
Console.Write("Enter URL Path to download image : ");
string path = Console.ReadLine();
Console.Write("Enter Filename : ");
string filename = Console.ReadLine();
WebClient wc = new WebClient();
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
fullpath = desktop + filename;
wc.DownloadFileAsync(new Uri(path), filename);
wc.DownloadFileCompleted += wc_DownloadFileCompleted;
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
string answer = Console.ReadLine();
if (answer == "y")
{
Process.Start(fullpath);
}
Console.WriteLine("Bye");
break;
}
catch (Exception ex)
{
Console.WriteLine("There was something not allwright with {0}", ex);
}
}
}
示例3: Start
void Start()
{
string[] arguments = Environment.GetCommandLineArgs();
ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
downloadLink = new Uri (arguments[2].ToString ().Substring (1, arguments[2].Length-1));
applicationLocation += arguments[1].ToString().Substring (1, arguments[1].Length -1) + "/UnityMusicPlayer";
Directory.Delete(applicationLocation + ".app", true);
guitext.text = "Downloading Update";
using (WebClient client = new WebClient())
try
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
client.DownloadProgressChanged += (start, end) => { progresstText.text = end.ProgressPercentage.ToString() + "%" ; };
client.DownloadFileAsync (downloadLink, applicationLocation + ".zip", 0);
} catch (Exception error) {
guitext.text = error.ToString ();
}
}
示例4: DownloadFile_InvalidArguments_ThrowExceptions
public static void DownloadFile_InvalidArguments_ThrowExceptions()
{
var wc = new WebClient();
Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((string)null, ""); });
Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((Uri)null, ""); });
Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, ""); });
Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, "", null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((string)null, ""); });
Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((Uri)null, ""); });
Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile("http://localhost", null); });
Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile(new Uri("http://localhost"), null); });
Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null); });
Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null, null); });
Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync("http://localhost", null); });
Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync(new Uri("http://localhost"), null); });
}
示例5: Main
static void Main(string[] args)
{
int timeout = 0;
if ((args.Length % 2) != 1 || args.Length == 1 || !int.TryParse(args[0], out timeout))
{
Console.WriteLine("Usage: download.exe <timeout_in_seconds> [<url> <output_file>]+");
Environment.Exit(1);
}
int n = 1;
int completed = 0;
ManualResetEvent waitHandle = new ManualResetEvent(false);
try
{
while (n < args.Length)
{
WebClient client = new WebClient();
int k = n;
client.DownloadFileCompleted += new AsyncCompletedEventHandler(delegate (object sender, AsyncCompletedEventArgs e) {
if (e.Error != null)
{
OnError(args[k], args[k + 1], e.Error);
}
Console.WriteLine("Finished download from " + args[k] + " to " + args[k + 1]);
if (++completed == ((args.Length - 1) / 2))
{
waitHandle.Set();
}
});
Console.WriteLine("Starting download from " + args[n] + " to " + args[n + 1]);
client.DownloadFileAsync(new Uri(args[n]), args[n + 1]);
n += 2;
}
}
catch (Exception e)
{
OnError(args[n], args[n + 1], e);
}
if (!waitHandle.WaitOne(new TimeSpan(0, 0, timeout)))
{
Console.WriteLine("Download timed out.");
Environment.Exit(1);
}
}
示例6: Download
void Download()
{
using (WebClient client = new WebClient())
try
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
client.DownloadProgressChanged += (start, end) => { currentDownloadPercentage = end.ProgressPercentage.ToString() + "%"; };
client.DownloadFileAsync (url, path + Path.DirectorySeparatorChar + file.name + "." + file.format);
} catch (Exception error)
{
UnityEngine.Debug.Log (error);
}
}
示例7: StartDelayedCache
internal static void StartDelayedCache(string url)
{
if (EnsureEnoughSpace())
{
Task.Delay(DelayAmount).ContinueWith(t =>
{
if (!IsCaching(url))
{
using (WebClient client = new WebClient())
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFileComplete);
string filename = Path.GetFileName(url);
client.DownloadFileAsync(new Uri(url), Path.Combine(TempFolder, filename), filename);
}
}
});
}
}
示例8: button_download_Click
private void button_download_Click(object sender, EventArgs e)
{
button_download.Enabled = false;
if (!_install) {
if (File.Exists(@"update.zip")) {
File.Delete(@"update.zip");
}
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(UpdateProgressBar);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(_update.Link), @"update.zip");
} else {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"updater.exe";
Process.Start(startInfo);
Application.Exit();
}
}
示例9: Main
public static void Main(string[] args)
{
var urls = Console.In.ReadToEnd().Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
var dir = args[0];
var taskList = new List<Task<bool>>(urls.Length);
foreach (var u in urls)
{
var wc = new WebClient();
var uri = new Uri(u);
var fileName = Path.Combine(dir, Path.GetFileName(u));
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
wc.DownloadFileCompleted += (sender, e) =>
{
if (e.Error != null)
{
Console.WriteLine("failed: {0}, {1}", uri, e.Error.Message);
tcs.TrySetResult(false);
}
else
{
Console.WriteLine("downloaded: {0} => {1}", uri, fileName);
tcs.TrySetResult(true);
}
};
wc.DownloadFileAsync(uri, fileName);
taskList.Add(tcs.Task);
}
Task.WaitAll(taskList.ToArray());
}
示例10: DownloadFile
public bool DownloadFile(string sURL, string sPath, string sFile)
{
bool bTimeout = false;
wc = new WebClient();
wc.UseDefaultCredentials = true;
this.bDownloadCancelled = false;
if (sPath.EndsWith("\\") == false)
sPath += "\\";
//sPath = sPath.Replace("?", "")
sPath = modFiles.ConvertToRealPath(sPath);
sFile = modFiles.ConvertToRealPath(sFile);
this.sPath = sPath;
this.sFile = sFile;
this.sURL = sURL;
if (Directory.Exists(sPath) == false) {
if (AllowAutoCreateFolder == false) {
SetStatusMessage(true, "DEFAULTFOLDER_NOT_AVAILABLE", sPath);
return false;
}
else {
try {
Directory.CreateDirectory(sPath);
if (Directory.Exists(sPath) == false) {
SetStatusMessage(true, "DEFAULTFOLDER_NOT_CREATEABLE", sPath);
return false;
}
} catch {
SetStatusMessage(true, "DEFAULTFOLDER_NOT_CREATEABLE", sPath);
return false;
}
}
}
if (File.Exists(sPath + sFile) == true) {
if (new FileInfo(sPath + sFile).Length > 0) {
if (AllowFileOverwrite == true) {
try {
File.Delete(sPath + sFile);
} catch {
SetStatusMessage(true, "FILE_NOT_OVERWRITEABLE", sPath + sFile);
return false;
}
} else {
SetStatusMessage(true, "FILE_ALREADY_EXISTS", sPath + sFile);
return false;
}
}
}
try {
wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)");
if (!string.IsNullOrEmpty(Referer)) {
wc.Headers.Add("Referer", Referer);
}
bDownloading = true;
tmrInit = false;
SetStatusMessage(false, "DOWNLOAD_START", sPath + sFile);
tmrDownloadSpeed.Start();
tmrTimeout.Start();
wc.DownloadFileAsync(new Uri(sURL), Path.Combine(sPath, sFile));
while ((this.bDownloading == true)) {
if (tmrTimeout.ElapsedMilliseconds >= (iTimeoutSec * 1000)) {
this.CancelDownload();
bTimeout = true;
break; // TODO: might not be correct. Was : Exit While
}
}
wc.Dispose();
tmrTimeout.Reset();
tmrDownloadSpeed.Reset();
if (bTimeout) {
SetStatusMessage(true, "DOWNLOAD_TIMEOUT", Path.Combine(sPath, sFile));
if (DeleteFileOnError)
File.Delete(Path.Combine(sPath, sFile));
return false;
}
if (this.bDownloadCancelled == true) {
this.bDownloadCancelled = false;
SetStatusMessage(false, "DOWNLOAD_CANCELLED", sPath + sFile);
if (DeleteFileOnError)
File.Delete(Path.Combine(sPath, sFile));
//.........这里部分代码省略.........
示例11: OnlineMusicBrowserPane
//.........这里部分代码省略.........
guiSkin.button.hover.background = guiHover;
if ( showSongInformation == true )
{
if ( songInfoOwner == song )
{
if ( downloading == false )
{
GUILayout.BeginHorizontal ();
GUILayout.FlexibleSpace ();
if ( GUILayout.Button ( downloadButtonText, buttonStyle ) && url != null )
{
if ( startupManager.developmentMode == true )
UnityEngine.Debug.Log ( url );
downloadingSong = song;
currentDownloadPercentage = " - Processing Download";
try
{
using ( client = new WebClient ())
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler ( DownloadFileCompleted );
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler( DownloadProgressCallback );
client.DownloadFileAsync ( url, startupManager.tempPath + song.name + "." + song.format );
}
} catch ( Exception error ) {
UnityEngine.Debug.Log ( error );
}
downloading = true;
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
} else {
GUILayout.Label ( "Downloading '" + downloadingSong.name + "'", labelStyle );
GUILayout.BeginHorizontal ();
GUILayout.FlexibleSpace ();
if ( GUILayout.Button ( "Cancel Download", buttonStyle ))
{
client.CancelAsync ();
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
}
if ( String.IsNullOrEmpty ( song.largeArtworkURL ) == false && downloadArtwork == true )
{
GUILayout.BeginHorizontal ();
GUILayout.FlexibleSpace ();
示例12: DisplayResults
private void DisplayResults()
{
if(responseProcessed_)
{
if(resetScroll_)
{
scroll_.x = scroll_.y = 0.0f;
resetScroll_ = false;
}
object[] sounds = (object[])response_["sounds"];
GUILayout.Label("Number of results: " + response_["num_results"].ToString());
int soundCounter = 0;
foreach(object sound in sounds)
{
var soundDictionary = (Dictionary<string, object>)sound;
GUILayout.BeginHorizontal();
GUILayout.Space(10);
if(GUILayout.Button(soundWaveforms_[soundCounter], waveformStyle_))
Application.OpenURL(soundDictionary["url"].ToString());
GUILayout.BeginVertical();
if(GUILayout.Button("\nPLAY\n"))
{
FreesoundAudioPlayer.Instance.StartStream(soundDictionary["preview-lq-ogg"].ToString());
}
GUILayout.Space(6);
if(GUILayout.Button("IMPORT"))
{
importPressed_ = true;
//TODO: refactor. Change WebClient to HttpWebRequest to handle timeouts better
importClient_ = new WebClient();
importClient_.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
importClient_.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
Uri request = new Uri(soundDictionary["serve"] + "?api_key=" + FreesoundHandler.Instance.ApiKey);
//If the user hasn't defined a default folder at Freesound configuration
//then create it at /Assets/Freesound/
if(String.IsNullOrEmpty(FreesoundHandler.Instance.FreesoundDownloadsPath))
{
System.IO.Directory.CreateDirectory(Application.dataPath + "/Freesound");
FreesoundHandler.Instance.FreesoundDownloadsPath = Application.dataPath + "/Freesound";
FreesoundHandler.Instance.FreesoundDownloads = "/Freesound";
}
string lastDownloadedFilePath = FreesoundHandler.Instance.FreesoundDownloadsPath +
"/" + soundDictionary["original_filename"].ToString();
try
{
importClient_.DownloadFileAsync(request, lastDownloadedFilePath);
//Cache log data to be used in async loading completion
Dictionary<string, object> userDataName = (Dictionary<string, object>)soundDictionary["user"];
lastData_.filename = soundDictionary["original_filename"].ToString();
lastData_.id = soundDictionary["id"].ToString();
lastData_.url = soundDictionary["url"].ToString();
lastData_.user = userDataName["username"].ToString();
lastData_.localPath = lastDownloadedFilePath;
}
catch(WebException e)
{
UnityEditor.EditorUtility.DisplayDialog("UnityFreesound Request ERROR!",
"Can't process the request." + "\n\nException thrown: " + e.Message,
"OK");
}
}
GUILayout.EndVertical();
GUILayout.BeginVertical();
EditorGUILayout.LabelField("File name", soundDictionary["original_filename"].ToString());
int point = soundDictionary["duration"].ToString().IndexOf(".");
if(point != -1)
{
if(soundDictionary["duration"].ToString().Length > 5)
EditorGUILayout.LabelField("Duration (secs)", soundDictionary["duration"].ToString().Substring(0, 5));
else
EditorGUILayout.LabelField("Duration (secs)", soundDictionary["duration"].ToString());
}
else
{
EditorGUILayout.LabelField("Duration (secs)", soundDictionary["duration"].ToString());
}
Dictionary<string, object> userData = (Dictionary<string, object>)soundDictionary["user"];
EditorGUILayout.LabelField("User", userData["username"].ToString());
//.........这里部分代码省略.........
示例13: ConcurrentOperations_Throw
public static async Task ConcurrentOperations_Throw()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
var wc = new WebClient();
Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
return Task.CompletedTask;
});
}
示例14: OnButton2Clicked
private void OnButton2Clicked(object sender, System.EventArgs e)
{
button1.Visible = true;
button3.Visible = false;
button4.Visible = false;
button2.Visible = false;
string path = System.IO.Path.GetTempPath();
XmlDocument current = new XmlDocument();
current.Load(Environment.CurrentDirectory + @"\Info.xml");
XmlNodeList update = current.GetElementsByTagName("updatexml");
XmlNodeList pro = current.GetElementsByTagName("ProgramName");
XmlNodeList ver1 = current.GetElementsByTagName("Installedversion");
string inversion = ver1[0].InnerText;
string updateurl = update[0].InnerText;
string prog = pro[0].InnerText;
XmlDocument updater = new XmlDocument();
updater.Load(updateurl);
XmlNodeList down = updater.GetElementsByTagName("InstallerURL");
XmlNodeList load = updater.GetElementsByTagName("InstallerNAME");
XmlNodeList ver2 = updater.GetElementsByTagName("LatestVersion");
string newversion = ver2[0].InnerText;
string installer = load[0].InnerText;
string install = down[0].InnerText + load[0].InnerText;
WebClient download = new WebClient();
label2.Text = "Downloading update for " + prog + ".";
label3.Text = "Please wait...";
label4.Text = "Downloading Version " + newversion + " installer. ";
download.DownloadProgressChanged += new DownloadProgressChangedEventHandler(download_DownloadProgressChanged);
download.DownloadFileCompleted += new AsyncCompletedEventHandler(download_DownloadFileCompleted);
if (System.IO.File.Exists(path + installer) == false)
{
download.DownloadFileAsync(new Uri(install), (path + installer));
}
else if (System.IO.File.Exists(path + installer) == true)
{
System.IO.File.Delete(path + installer);
download.DownloadFileAsync(new Uri(install), (path + installer));
}
}
示例15: rptrModule_ItemCommand
protected void rptrModule_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "DownLoad")
{
string url = e.CommandArgument.ToString();
WebClient client = new WebClient();
try
{
string fileName = Path.GetFileName(url);
hdnFileName.Value = fileName;
string path = HttpContext.Current.Server.MapPath("~/");
string temPath = SageFrame.Common.RegisterModule.Common.TemporaryFolder;
string destPath = Path.Combine(path, temPath);
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileAsync(new Uri(url), Server.MapPath(string.Format("~/Install/Temp/{0}", fileName)));
}
catch (Exception)
{
client.Dispose();
throw;
}
}
}