本文整理汇总了C#中System.Net.WebClient.DownloadDataTaskAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.DownloadDataTaskAsync方法的具体用法?C# WebClient.DownloadDataTaskAsync怎么用?C# WebClient.DownloadDataTaskAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.DownloadDataTaskAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProfileImage
public async Task<IActionResult> ProfileImage(string domain, string login)
{
using (var client = new WebClient())
{
var uri = string.Format(_appSettings.Options.SharePointImageUrl, domain, login);
var data = await client.DownloadDataTaskAsync(uri);
return File(data, "image/jpeg");
}
}
示例2: BeginDownloadMinecraft
public static async Task BeginDownloadMinecraft(this MainWindow window)
{
window.LoadingBox.Visibility = Visibility.Visible;
window.LoadingText.Content = "Updating Minecraft...";
window.LoadingProgress.IsIndeterminate = true;
if (!Directory.Exists(Globals.LauncherDataPath + @"\Minecraft")) Directory.CreateDirectory(Globals.LauncherDataPath + @"\Minecraft");
if (!Directory.Exists(Globals.LauncherDataPath + @"\Minecraft\bin")) Directory.CreateDirectory(Globals.LauncherDataPath + @"\Minecraft\bin");
if (!Directory.Exists(Globals.LauncherDataPath + @"\Minecraft\bin\natives")) Directory.CreateDirectory(Globals.LauncherDataPath + @"\Minecraft\bin\natives");
WebClient c = new WebClient();
try
{
if ((long)Settings.Default["CachedLWJGLTimestamp"] == null || LauncherInformation.Current.LWJGLTimestamp > (long)Settings.Default["CachedLWJGLTimestamp"])
{
window.LoadingText.Content = "Downloading updated LWJGL...";
byte[] d = await c.DownloadDataTaskAsync(LauncherInformation.Current.LWJGLLocation);
ZipFile f = ZipFile.Read(new MemoryStream(d));
f.ExtractAll(Globals.LauncherDataPath + @"\Minecraft\bin", ExtractExistingFileAction.OverwriteSilently);
Settings.Default["CachedLWJGLTimestamp"] = LauncherInformation.Current.LWJGLTimestamp;
Settings.Default.Save();
}
if((long)Settings.Default["CachedMinecraftTimestamp"] == null || LauncherInformation.Current.MinecraftTimestamp > (long)Settings.Default["CachedMinecraftTimestamp"])
{
MessageBoxResult r = MessageBox.Show("Do you want to update Minecraft? (Latest version: " + LauncherInformation.Current.MinecraftVersion + ")", "MCLauncher", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (r == MessageBoxResult.Yes)
{
window.LoadingText.Content = "Downloading Minecraft " + LauncherInformation.Current.MinecraftVersion + "...";
byte[] mc = await c.DownloadDataTaskAsync(LauncherInformation.Current.MinecraftLocation);
File.WriteAllBytes(Globals.LauncherDataPath + @"\Minecraft\bin\minecraft.jar", mc);
Settings.Default["CachedMinecraftTimestamp"] = LauncherInformation.Current.MinecraftTimestamp;
Settings.Default.Save();
}
}
}
catch (WebException ex)
{
MessageBox.Show("Failed to update Minecraft. Is your internet down? Exception information: " + ex.ToString(), "An error has occured.", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
c.Dispose();
}
}
示例3: RunFetchLoopAsync
private static async void RunFetchLoopAsync(IActorRef publisher, string url, string source)
{
await Task.Yield();
try
{
var c = new WebClient();
while (true)
{
var data = await c.DownloadDataTaskAsync(new Uri(url));
var str = Encoding.UTF8.GetString(data);
dynamic res = JsonConvert.DeserializeObject(str);
// Console.WriteLine("Downloaded {0}",url);
foreach (var bus in res)
{
string id = bus.ID;
double lat = bus.Latitude;
double lon = bus.Longitude;
publisher.Tell(new Presenter.Position(lon, lat, id, source));
}
//how long should we wait before polling again?
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
catch
{
Console.WriteLine("Missing Route {0}", url);
}
}
示例4: downloadImage
private async Task<byte[]> downloadImage(string path)
{
using (var wb = new WebClient())
{
return await wb.DownloadDataTaskAsync(path);
}
}
示例5: DownloadPageAsync
public static async Task<string> DownloadPageAsync(string path)
{
using (var webClient = new WebClient())
{
return Encoding.UTF8.GetString(await webClient.DownloadDataTaskAsync(path));
}
}
示例6: DownloadDataTaskAsyncWhenCancellationTokenAndUriIsNullTest
public void DownloadDataTaskAsyncWhenCancellationTokenAndUriIsNullTest()
{
var webClient = new WebClient();
var exception = Assert.Throws<ArgumentNullException>(() => webClient.DownloadDataTaskAsync(null, new CancellationToken()));
Assert.AreEqual("uri", exception.ParamName);
}
示例7: GetPageSize
public async Task<long> GetPageSize(CancellationToken cToken)
{
WebClient wc = new WebClient();
Stopwatch sw = Stopwatch.StartNew();
byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl);
Debug.WriteLine("Elapsed ms: {0}", sw.ElapsedMilliseconds);
return apressData.LongLength;
//List<long> results = new List<long>();
//for (int i = 0; i < 10; i++)
//{
// if (!cToken.IsCancellationRequested)
// {
// Debug.WriteLine("Making Request: {0}", i);
// byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl);
// results.Add(apressData.LongLength);
// }
// else
// {
// Debug.WriteLine("Cancelled");
// return 0;
// }
//}
////byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl);
//Debug.WriteLine("Elapsed ms: {0}", sw.ElapsedMilliseconds);
////return apressData.LongLength;
//return (long)results.Average();
}
示例8: GetAsByteArrayAsync
public Task<byte[]> GetAsByteArrayAsync()
{
using (var webClient = new WebClient())
{
return webClient.DownloadDataTaskAsync(_url);
}
}
示例9: DownloadProfilePhoto
private static async Task<byte[]> DownloadProfilePhoto(string profileUrlString, byte[] emptyPhotoBytes)
{
var webClient = new WebClient();
webClient.UseDefaultCredentials = true;
byte[] blobBytes = new byte[emptyPhotoBytes.Length];
try
{
blobBytes = await webClient.DownloadDataTaskAsync(profileUrlString);
}
catch (WebException webException)
{
if (webException.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)webException.Response).StatusCode == HttpStatusCode.NotFound)
{
emptyPhotoBytes.CopyTo(blobBytes, 0);
}
}
else if (webException.Status == WebExceptionStatus.NameResolutionFailure)
{
emptyPhotoBytes.CopyTo(blobBytes, 0);
}
else
{
throw webException;
}
}
return blobBytes;
}
示例10: DownloadAndRunAsync
public async Task DownloadAndRunAsync()
{
if (string.IsNullOrWhiteSpace(SupportUrl))
{
throw Log.ErrorAndCreateException<InvalidOperationException>("Please initialize the service by setting the SupportUrl property");
}
Log.Info("Downloading support app from '{0}'", SupportUrl);
var webClient = new WebClient();
webClient.DownloadProgressChanged += OnWebClientOnDownloadProgressChanged;
webClient.DownloadDataCompleted += OnWebClientOnDownloadDataCompleted;
var data = await webClient.DownloadDataTaskAsync(SupportUrl);
Log.Info("Support app is downloaded, storing file in temporary folder");
var tempDirectory = Path.Combine(Path.GetTempPath(), "Orc_AutomaticSupport", DateTime.Now.ToString("yyyyMMddHHmmss"));
if (!Directory.Exists(tempDirectory))
{
Directory.CreateDirectory(tempDirectory);
}
var tempFile = Path.Combine(tempDirectory, "SupportApp.exe");
File.WriteAllBytes(tempFile, data);
Log.Info("Running support app");
_processService.StartProcess(tempFile, CommandLineParameters, exitCode =>
{
_dispatcherService.BeginInvoke(() => SupportAppClosed.SafeInvoke(this));
});
}
示例11: DownloadData
[Category("AndroidNotWorking")] // Attempts to access the test dll which won't work on Android
public void DownloadData ()
{
WebClient wc;
bool progress_changed = false;
bool completed = false;
bool progress_changed_error = false;
bool completed_error = false;
int thread_id = Thread.CurrentThread.ManagedThreadId;
wc = new WebClient ();
wc.DownloadProgressChanged += delegate {
progress_changed = true;
if (Thread.CurrentThread.ManagedThreadId != thread_id)
progress_changed_error = true;
};
wc.DownloadDataCompleted += delegate {
completed = true;
if (Thread.CurrentThread.ManagedThreadId != thread_id)
completed_error = true;
};
MessagePumpSyncContext.Run (async () => {
var url = Assembly.GetExecutingAssembly ().CodeBase;
await wc.DownloadDataTaskAsync (url);
Assert.AreEqual (Thread.CurrentThread.ManagedThreadId, thread_id);
}, () => progress_changed && completed, 10000);
Assert.IsTrue (progress_changed, "#1");
Assert.IsFalse (progress_changed_error, "#2");
Assert.IsTrue (completed, "#3");
Assert.IsFalse (completed_error, "#4");
}
示例12: Main
public static void Main(string[] args)
{
var urls = Console.In.ReadToEnd().Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
var dir = args[0];
Func<string, Task> download = async (url) => {
var wc = new WebClient();
var uri = new Uri(url);
var fileName = Path.Combine(dir, Path.GetFileName(url));
try {
byte[] buf = await wc.DownloadDataTaskAsync(uri);
using (var fs = new FileStream(fileName, FileMode.Create))
{
await fs.WriteAsync(buf, 0, buf.Length);
}
Console.WriteLine("download: {0} => {1}", url, fileName);
} catch (Exception ex) {
Console.WriteLine("failed: {0}, {1}", url, ex.Message);
}
};
Task.WaitAll((from url in urls select download(url)).ToArray());
}
示例13: ResetAsync
public async Task ResetAsync(string CalculatorId)
{
using (var client = new WebClient())
{
await client.DownloadDataTaskAsync(new Uri(this.url + "reset?id=" + CalculatorId));
}
}
示例14: CreateObservableTimePoller
private static IObservable<byte[]> CreateObservableTimePoller()
{
return Observable.Create<byte[]>(observer =>
{
var scheduler = Scheduler.Default;
return scheduler.ScheduleAsync(async (schedulerController, cancelletionToken) =>
{
while (!cancelletionToken.IsCancellationRequested)
{
var client = new WebClient();
client.Headers.Add("user-agent",
@"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");
try
{
var result = await client.DownloadDataTaskAsync("http://www.timeapi.org/utc/now");
observer.OnNext(result);
}
catch (Exception ex)
{
Console.WriteLine(ex);
observer.OnError(ex);
}
await schedulerController.Sleep(TimeSpan.FromMilliseconds(500), cancelletionToken);
}
});
});
}
示例15: GetSongIdMap
private async Task<Dictionary<string, SongInfo[]>> GetSongIdMap(bool remote)
{
try
{
if (remote)
{
using (var client = new WebClient())
{
var data = await client.DownloadDataTaskAsync(new Uri($"https://apiv2.deresute.info/data/live"));
using (var stream = new MemoryStream(data))
{
Directory.CreateDirectory("data/patterns");
File.WriteAllBytes($"data/patterns/index", data);
return ParseSongIdMap(stream);
}
}
}
else
{
using (var fs = File.OpenRead($"data/patterns/index"))
{
return ParseSongIdMap(fs);
}
}
}
catch
{
return null;
}
}