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


C# WebClient.DownloadDataTaskAsync方法代码示例

本文整理汇总了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");
     }
 }
开发者ID:Alexandre-Machado,项目名称:SkillMap,代码行数:9,代码来源:HomeController.cs

示例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();
            }
            
        }
开发者ID:tman0,项目名称:MCLauncher2,代码行数:48,代码来源:WebInterface.cs

示例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);
            }
        }
开发者ID:mindis,项目名称:TaxiDemo,代码行数:31,代码来源:LadotProvider.cs

示例4: downloadImage

 private async Task<byte[]> downloadImage(string path)
 {
     using (var wb = new WebClient())
     {
         return await wb.DownloadDataTaskAsync(path);
     }
 }
开发者ID:kellmiir,项目名称:SerialsSubscriber,代码行数:7,代码来源:ExSerialParser.cs

示例5: DownloadPageAsync

 public static async Task<string> DownloadPageAsync(string path)
 {
     using (var webClient = new WebClient())
     {
         return Encoding.UTF8.GetString(await webClient.DownloadDataTaskAsync(path));
     }
 }
开发者ID:kellmiir,项目名称:SerialsSubscriber,代码行数:7,代码来源:DownLoader.cs

示例6: DownloadDataTaskAsyncWhenCancellationTokenAndUriIsNullTest

        public void DownloadDataTaskAsyncWhenCancellationTokenAndUriIsNullTest()
        {
            var webClient = new WebClient();
            var exception = Assert.Throws<ArgumentNullException>(() => webClient.DownloadDataTaskAsync(null, new CancellationToken()));

            Assert.AreEqual("uri", exception.ParamName);
        }
开发者ID:vivet,项目名称:GoogleApi,代码行数:7,代码来源:WebClientExtensionTest.cs

示例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();
        }
开发者ID:knolegsb,项目名称:WebApiPrimer,代码行数:30,代码来源:PageSizeController.cs

示例8: GetAsByteArrayAsync

 public Task<byte[]> GetAsByteArrayAsync()
 {
     using (var webClient = new WebClient())
     {
         return webClient.DownloadDataTaskAsync(_url);
     }
 }
开发者ID:Bomret,项目名称:Sourcery,代码行数:7,代码来源:UrlSource.cs

示例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;
        }
开发者ID:Bowman74,项目名称:Badge-Application,代码行数:31,代码来源:ImageController.cs

示例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));
            });
        }
开发者ID:telefunkenvf14,项目名称:Orc.AutomaticSupport,代码行数:35,代码来源:AutomaticSupportService.cs

示例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");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:35,代码来源:WebClientTestAsync.cs

示例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());
	}
开发者ID:kirigishi123,项目名称:try_samples,代码行数:27,代码来源:AsyncDownloadWeb2.cs

示例13: ResetAsync

 public async Task ResetAsync(string CalculatorId)
 {
     using (var client = new WebClient())
     {
         await client.DownloadDataTaskAsync(new Uri(this.url + "reset?id=" + CalculatorId));
     }
 }
开发者ID:unbornchikken,项目名称:workflow-4-node-examples,代码行数:7,代码来源:WF4NodeClient.cs

示例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);
             }
         });
     });
 }
开发者ID:jcteague,项目名称:rxtests,代码行数:27,代码来源:Program.cs

示例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;
     }
 }
开发者ID:noelex,项目名称:Cindeck,代码行数:30,代码来源:PatternProvider.cs


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