public DownloadFileTaskAsync ( System address, string fileName ) : System.Threading.Tasks.Task | ||
address | System | |
fileName | string | |
return | System.Threading.Tasks.Task |
/// <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; }
private async void startdwButton_Click(object sender, EventArgs e) { if (folderTextBox.Text != "" && urlTextBox.Text != "") { startdwButton.Enabled = false; folderTextBox.Enabled = false; filenameTextBox.Enabled = false; fileextensionTextBox.Enabled = false; urlTextBox.Enabled = false; string url = @"" + urlTextBox.Text; string filepath = @"" + folderTextBox.Text; Uri uri = new Uri(url); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownLoadCompleted); webClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(ProgressChanged); pbWIDTH = CastomProgressBar.Width; pbHEIGHT = CastomProgressBar.Height; pbUnit = pbWIDTH / 100.0; pbComplete = 0; bitmap = new Bitmap(pbWIDTH, pbHEIGHT); graphics = Graphics.FromImage(bitmap); graphics.Clear(Color.FromArgb(101, 144, 188)); if (ProxyTextBox.Text != "") { WebProxy webProxy = new WebProxy(); Uri proxyUri = new Uri(ProxyTextBox.Text); webProxy.Address = proxyUri; if (UserNameTextBox.Text != "" && UserNameTextBox.Text != "") { webProxy.Credentials = new NetworkCredential(UserNameTextBox.Text, PasswordTextBox.Text); } webClient.Proxy = webProxy; await webClient.DownloadFileTaskAsync(url, filepath); } else { await webClient.DownloadFileTaskAsync(url, filepath); } } else { MessageForm messageForm = new MessageForm(); messageForm.HandleLabel.Text = "Download"; messageForm.Text = "Download"; messageForm.TextLabel.Text = "Please, enter url or select folder!"; messageForm.ShowDialog(); //MessageBox.Show("Please, enter url or select folder!", "Download", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public async Task DownloadImage(string filePath, string url) { using (WebClient client = new WebClient()) { await client.DownloadFileTaskAsync(url, filePath); } }
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) { } }
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) { } }
protected async Task <string> SaveFileDataFromWebClient(string absoluteUrl, string filePath) { SslTruster.TrustSslIfAppSettingConfigured(); try { if (absoluteUrl == null || absoluteUrl == "#") { return(null); } using (var client = new System.Net.WebClient()) { client.Encoding = DefaultEncoder; await client.DownloadFileTaskAsync(new Uri(absoluteUrl), filePath); } return(filePath); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine("error while publishing to file " + ex.Message); //throw; } return(null); }
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); })); } }
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; }
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); }
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); } }
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(); }
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 _(._.)_"); } }
/// <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); } }
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 { } } } } }
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); } }
/// <summary> /// Downloads a file from the Internet (http, https) /// </summary> /// <param name="remoteUrl"></param> /// <param name="localFileName"></param> public static async Task DownloadFileAsync(string remoteUrl, string localFileName) { using (var wc = new System.Net.WebClient()) { wc.BaseAddress = remoteUrl; await wc.DownloadFileTaskAsync(new Uri(remoteUrl), localFileName); } }
/// <summary> /// Downloads the file. /// </summary> /// <param name="serverPath">The server path.</param> /// <param name="localPath">The local path.</param> private static async Task downloadFile(string serverPath, string localPath) { using (System.Net.WebClient wb = new System.Net.WebClient()) { wb.DownloadProgressChanged += downloadProgressChanged; await wb.DownloadFileTaskAsync(new Uri(serverPath), localPath); } }
/// <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); } }
public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data, NameValueCollection values) { System.Net.WebClient webclient = new System.Net.WebClient(); // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file" //webclient.Download * (...); // Any method starting with "Download" webclient.DownloadData(address); // Noncompliant webclient.DownloadDataAsync(uriAddress, new object()); // Noncompliant webclient.DownloadDataTaskAsync(uriAddress); // Noncompliant webclient.DownloadFile(address, "filename"); // Noncompliant webclient.DownloadFileAsync(uriAddress, "filename"); // Noncompliant webclient.DownloadFileTaskAsync(address, "filename"); // Noncompliant webclient.DownloadString(uriAddress); // Noncompliant webclient.DownloadStringAsync(uriAddress, new object()); // Noncompliant webclient.DownloadStringTaskAsync(address); // Noncompliant // Should not raise for events webclient.DownloadDataCompleted += Webclient_DownloadDataCompleted; webclient.DownloadFileCompleted += Webclient_DownloadFileCompleted; webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged; webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted; //webclient.Open * (...); // Any method starting with "Open" webclient.OpenRead(address); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Make sure that this http request is sent safely.}} webclient.OpenReadAsync(uriAddress, new object()); // Noncompliant webclient.OpenReadTaskAsync(address); // Noncompliant webclient.OpenWrite(address); // Noncompliant webclient.OpenWriteAsync(uriAddress, "STOR", new object()); // Noncompliant webclient.OpenWriteTaskAsync(address, "POST"); // Noncompliant webclient.OpenReadCompleted += Webclient_OpenReadCompleted; webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted; //webclient.Upload * (...); // Any method starting with "Upload" webclient.UploadData(address, data); // Noncompliant webclient.UploadDataAsync(uriAddress, "STOR", data); // Noncompliant webclient.UploadDataTaskAsync(address, "POST", data); // Noncompliant webclient.UploadFile(address, "filename"); // Noncompliant webclient.UploadFileAsync(uriAddress, "filename"); // Noncompliant webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant webclient.UploadString(uriAddress, "data"); // Noncompliant webclient.UploadStringAsync(uriAddress, "data"); // Noncompliant webclient.UploadStringTaskAsync(uriAddress, "data"); // Noncompliant webclient.UploadValues(address, values); // Noncompliant webclient.UploadValuesAsync(uriAddress, values); // Noncompliant webclient.UploadValuesTaskAsync(address, "POST", values); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Should not raise for events webclient.UploadDataCompleted += Webclient_UploadDataCompleted; webclient.UploadFileCompleted += Webclient_UploadFileCompleted; webclient.UploadProgressChanged -= Webclient_UploadProgressChanged; webclient.UploadStringCompleted -= Webclient_UploadStringCompleted; webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted; }
public void Start() { using (var client = new WebClient()) { client.Proxy = Utilities.GetProxyWithCredentials(); client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileTaskAsync(URL, Path).Wait(); } }
private async void DownloadLoadingImage() { if (!Directory.Exists("Resource/Images")) Directory.CreateDirectory("Resource/Images"); if (File.Exists(Param.LoadingImageLocal)) File.Delete(Param.LoadingImageLocal); using (var client = new WebClient()) { await client.DownloadFileTaskAsync(new Uri(Param.LoadingImageUrl), Param.LoadingImageLocal); } }
private async static Task GetRequestFile(string url) { using (var client = new WebClient()) { client.Headers.Add("user-agent", "my own code"); client.DownloadProgressChanged += client_DownloadProgressChanged; await client.DownloadFileTaskAsync(url, @"asdf"); } }
private static async Task Update(string version) { try { var filePath = string.Format("temp/v{0}.zip", version); Console.WriteLine("Creating temp file directory"); if(Directory.Exists("temp")) Directory.Delete("temp", true); Directory.CreateDirectory("temp"); using(var wc = new WebClient()) { var lockThis = new object(); Console.WriteLine("Downloading latest version... 0%"); wc.DownloadProgressChanged += (sender, e) => { lock(lockThis) { Console.CursorLeft = 0; Console.CursorTop = 1; Console.WriteLine("Downloading latest version... {0}/{1}KB ({2}%)", e.BytesReceived / (1024), e.TotalBytesToReceive / (1024), e.ProgressPercentage); } }; await wc.DownloadFileTaskAsync(string.Format(Url, version), filePath); } File.Move(filePath, filePath.Replace("rar", "zip")); Console.WriteLine("Extracting files..."); ZipFile.ExtractToDirectory(filePath, "temp"); const string newPath = "temp\\Hearthstone Deck Tracker\\"; CopyFiles("temp", newPath); Process.Start("Hearthstone Deck Tracker.exe"); } catch { Console.WriteLine("There was a problem updating to the latest version. Pressing any key will direct you to the manual download."); Console.ReadKey(); Process.Start(@"https://github.com/Epix37/Hearthstone-Deck-Tracker/releases"); } finally { try { Console.WriteLine("Cleaning up..."); if(Directory.Exists("temp")) Directory.Delete("temp", true); Console.WriteLine("Done!"); } catch { Console.WriteLine("Failed to delete temp file directory"); } } }
private async void bwDownloadGif_DoWork(object sender, DoWorkEventArgs e) { if (!Directory.Exists("Resource/Images")) Directory.CreateDirectory("Resource/Images"); if (File.Exists(Param.LoadingImageLocal)) File.Delete(Param.LoadingImageLocal); using (var client = new WebClient()) { await client.DownloadFileTaskAsync(new Uri(Param.LoadingImageUrl), Param.LoadingImageLocal); } }
public Task DownloadFile(string url, string targetFile) { var wc = new WebClient(); this.Log().Info("Downloading file: " + url); return this.WarnIfThrows(() => wc.DownloadFileTaskAsync(url, targetFile), "Failed downloading URL: " + url); }
public static Task DownloadAndRun(string url) { WebClient wc = new WebClient(); Uri uri = new Uri(url); wc.DownloadProgressChanged += (sender, args) => { Console.Write("\r" + (((double)args.BytesReceived / args.TotalBytesToReceive)*100).ToString("00.##") + "%"); }; wc.DownloadFileCompleted += (sender, args) => { Process.Start(System.IO.Path.GetFileName(uri.LocalPath)); }; Task ret = wc.DownloadFileTaskAsync(uri, System.IO.Path.GetFileName(uri.LocalPath)); Console.WriteLine("Load progress:"); return ret; }
private Task DownloadTask(string downloadFrom, string destination) { using (WebClient client = new WebClient()) { client.DownloadProgressChanged += this.OnDownloadProgress; client.DownloadFileCompleted += this.OnDownloadComplete; return client.DownloadFileTaskAsync(new Uri(downloadFrom), destination); } }
private async Task DownloadUpdate(string url) { using (System.Net.WebClient client = new System.Net.WebClient()) { client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged); await client.DownloadFileTaskAsync(new Uri(url), Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/update.zip")); InstallUpdate(); } }
public static async Task DownloadSoundCloudTrack(string soundCloudId, string fileName, Action<double> progressChangedAction) { using (var client = new WebClient { Proxy = null }) { client.DownloadProgressChanged += (s, e) => progressChangedAction.Invoke(e.ProgressPercentage); await client.DownloadFileTaskAsync( string.Format("https://api.soundcloud.com/tracks/{0}/download?client_id={1}", soundCloudId, SensitiveInformation.SoundCloudKey), fileName); } }
public void DownloadFileTaskAsync () { WebClient wc = new WebClient (); string filename = Path.GetTempFileName (); var task = wc.DownloadFileTaskAsync ("http://www.mono-project.com/", filename); task.Wait (); Assert.IsTrue (task.IsCompleted); File.Delete (filename); }
private static void DoDownload(string url, string filename) { using (var wc = new WebClient()) { Console.WriteLine("Downloading [{0}] to [{1}]...", url, filename); var task = wc.DownloadFileTaskAsync(url, filename); while (task.Status == TaskStatus.Running) { Console.Write("."); } } }
static Task GetDownload(string url, string fileName) { lock (locker) { Task task; if (downloadTasks.TryGetValue (fileName, out task)) return task; var client = new WebClient (); downloadTasks.Add (fileName, task = client.DownloadFileTaskAsync (url, fileName)); return task; } }
public Task Download(string path) { using (var webClient = new WebClient {Proxy = null}) { webClient.DownloadProgressChanged += (sender, args) => DownloadProgressChanged?.Invoke(this, new DownloadProgressChangedEventArgs(args.BytesReceived, args.TotalBytesToReceive)); return webClient.DownloadFileTaskAsync(_downloadUrl, path); } }
private async Task DownloadFileAsync(string url, string cookie, string file) { WebClient wc = new WebClient(); wc.Headers.Add(HttpRequestHeader.Cookie, $"EYBSN={cookie}; EYBID={username}"); wc.Headers.Add(HttpRequestHeader.Host, "www.e-yearbook.com"); wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"); wc.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); wc.Headers.Add(HttpRequestHeader.KeepAlive, "300"); wc.Headers.Add(HttpRequestHeader.Accept, "image/webp,image/*,*/*;q=0.8"); wc.Headers.Add(HttpRequestHeader.CacheControl, "no-cache"); wc.Headers.Add(HttpRequestHeader.Referer, "http://www.e-yearbook.com/sp/eybb"); await wc.DownloadFileTaskAsync(url, file); }
private static async Task<string> SendTranslationRequestAsync(string sourceText, Language sourceLanguage, Language targetLanguage) { var requestUrl = CreateRequestUrl(sourceText, sourceLanguage, targetLanguage); var outputFile = Path.GetTempFileName(); using (var webClient = new WebClient()) { webClient.Headers.Add("user-agent", UserAgent); await webClient.DownloadFileTaskAsync(requestUrl, outputFile); } return outputFile; }
private static async Task SaveUrlToFile(string url, string fileName) { try { using (WebClient client = new WebClient()) { await client.DownloadFileTaskAsync(url, fileName); } } catch (Exception ex) { Logger.Log(ex); } }
public async void RequestFromWeb() { //Downloads the text file then deletes the file at the url. // String logFilePath = RequestParser.GetCurrentWorkingDirectory() + "\\NewJobs\\testdelete.txt"; using (var wc = new System.Net.WebClient()) { await wc.DownloadFileTaskAsync(new Uri("****"), @"C:\****"); //directory needs to be fixed } HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://.php"); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); }
public static async Task DownloadFileAsync(string url, string saveTo) { var wc = new System.Net.WebClient { Headers = { [HttpRequestHeader.UserAgent] = WII_USER_AGENT } }; wc.DownloadProgressChanged += DownloadProgressChanged; await wc.DownloadFileTaskAsync(new Uri(url), saveTo); while (wc.IsBusy) { await Task.Delay(100); } wc.Dispose(); }
public static async Task <bool> DownloadFile(string url, string path, bool redownloadIfAlreadyExists = false, TimeSpan?redownloadIfOlderThan = null) { try { if (File.Exists(path)) { if (!redownloadIfAlreadyExists) { return(true); } if (redownloadIfOlderThan.HasValue && (DateTime.Now - File.GetCreationTime(path)) <= redownloadIfOlderThan.Value) { return(true); } File.Delete(path); } var dirPath = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dirPath)) { Directory.CreateDirectory(dirPath); } using (var wc = new System.Net.WebClient()) { await wc.DownloadFileTaskAsync(url, path); } } catch (System.Net.WebException ex) { if (File.Exists(path)) { File.Delete(path); } return(false); } catch (OperationCanceledException) { if (File.Exists(path)) { File.Delete(path); } return(false); } return(true); }
private async Task SimpleDownload(string link, string fileName, float step, SynchronizationContext context) { using (var client = new System.Net.WebClient()) { Task task = client.DownloadFileTaskAsync(link, fileName); await task; if (task.Exception != null) { throw task.Exception.InnerException; } _currentProgress += step; context.Post(new SendOrPostCallback((o) => { OnProgressReportUpdate(new ProgressReportUpdateEventArgs(_currentProgress)); }), null); } }
static async void Example11() { System.Net.WebClient wc = new System.Net.WebClient(); wc.DownloadProgressChanged += (sender, args) => { Console.WriteLine(args.ProgressPercentage + "% complete"); }; await Task.Delay(5000).ContinueWith(ant => wc.CancelAsync()); try { await wc.DownloadFileTaskAsync("https://www.oreilly.com/", "code.html"); } catch (WebException we) { Console.WriteLine(we.Status == WebExceptionStatus.RequestCanceled); } }
/// <summary> /// Downloads a file from HTTP to a local file on disk on the web server. /// </summary> /// <param name="httpUrl">The URL of the file to download.</param> /// <returns>A task containing the downloaded file name..</returns> private async Task <string> DownloadFileLocally(Uri httpUrl) { var appData = Path.Combine(hosting.ContentRootPath, "App_Data"); if (!Directory.Exists(appData)) { Directory.CreateDirectory(appData); } var tempFilePath = Path.Combine(appData, Path.GetRandomFileName()); using (var downloader = new System.Net.WebClient()) { await downloader.DownloadFileTaskAsync(httpUrl, tempFilePath); } return(tempFilePath); }
private async Task CheckForUpdates(bool Silent) { System.Net.WebClient webClient = new System.Net.WebClient(); System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); var result = await httpClient.GetAsync("https://lucency.co/Services/VersionCheck?Path=/Downloads/CleanShot.exe"); var serverVersion = Version.Parse(await result.Content.ReadAsStringAsync()); var thisVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (serverVersion > thisVersion) { var strFilePath = System.IO.Path.GetTempPath() + "CleanShot.exe"; var msgResult = System.Windows.MessageBox.Show("A new version of CleanShot is available! Would you like to download it now? It's a no-fuss, instant process.", "New Version Available", MessageBoxButton.YesNo, MessageBoxImage.Question); if (msgResult == MessageBoxResult.Yes) { if (File.Exists(strFilePath)) { File.Delete(strFilePath); } try { await webClient.DownloadFileTaskAsync(new Uri("https://lucency.co/Downloads/CleanShot.exe"), strFilePath); } catch { if (!Silent) { System.Windows.MessageBox.Show("Unable to contact the server. Check your network connection or try again later.", "Server Unreachable", MessageBoxButton.OK, MessageBoxImage.Exclamation); } return; } Process.Start(strFilePath, "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\""); App.Current.Shutdown(); return; } } else { if (!Silent) { System.Windows.MessageBox.Show("CleanShot is up-to-date.", "No Updates", MessageBoxButton.OK, MessageBoxImage.Information); } } }
public static async Task <(bool success, string downloadedFilePath)> DownloadFileWebClientAsync(string url, string downloadFileRootPath, string fileNameNoExtension, IProgress <int> progress, CancellationToken stop) { var downloadFileLocation = GetDownloadFilePath(downloadFileRootPath, fileNameNoExtension, GetFileExtension(url)); var downloadStatus = false; using (var client = new System.Net.WebClient()) { client.Proxy = null; client.DownloadProgressChanged += (s, e1) => { progress?.Report(e1.ProgressPercentage); }; client.DownloadFileCompleted += (s, e) => { downloadStatus = !e.Cancelled && e.Error == null; }; stop.Register(client.CancelAsync); // Starts the download await client.DownloadFileTaskAsync(new Uri(url), downloadFileLocation); } return(downloadStatus, downloadFileLocation); }
/// <summary> /// Scarica un file in asincrono. /// </summary> /// <param name="Url">L'Url da dove prelevare il file</param> /// <param name="Destination">La destinazione locale dove salvarlo</param> /// <param name="WriteOnBuffer">Se deve scaricare i dati (alcune estensioni hanno problemi con downloadfile)</param> public static async UniTask <bool> DownloadFileAsync(string Url, string Destination, bool WriteOnBuffer = false) { try { if (WriteOnBuffer) { System.Net.WebClient webClient = new System.Net.WebClient(); byte[] buffer = await webClient.DownloadDataTaskAsync(Url); File.WriteAllBytes(Destination, buffer); webClient.Dispose(); } else { System.Net.WebClient webClient = new System.Net.WebClient(); await webClient.DownloadFileTaskAsync(Url, Destination); webClient.Dispose(); } } catch (Exception e) { LogE("Utilities", "Errore DownloadFile: [" + e + "]"); return(false); } return(true); }
private async Task <string> AsyncReadWeb() { string localfile; string fileName = GetLocalFile(out localfile); if (string.IsNullOrEmpty(fileName)) { using (var client = new System.Net.WebClient()) { if (!File.Exists(fileName)) { try { await client.DownloadFileTaskAsync(VoicePath, localfile); } catch (WebException) { try { File.Delete(localfile); } catch (FileNotFoundException) { } return(string.Empty); } FileInfo file = new FileInfo(localfile); if (file.Extension == ".amr") { localfile = ChangeAMR(localfile); } return(localfile); } } } return(fileName); }
string MakeSureLibraryIsInPlace(string destinationBase, string url, string version, string embeddedArchive, string sha1) { if (string.IsNullOrEmpty(url)) { return(null); } Log.LogDebugMessage("Making sure we have {0} downloaded and extracted {1} from it...", url, embeddedArchive); string destinationDir = version == null ? destinationBase : Path.Combine(destinationBase, version); bool createDestinationDirectory = !Directory.Exists(destinationDir); if (createDestinationDirectory) { Directory.CreateDirectory(destinationDir); } var hash = string.Concat(md5.ComputeHash(Encoding.UTF8.GetBytes(url)).Select(b => b.ToString("X02"))); var uri = new Uri(url); string zipDir = !uri.IsFile ? Path.Combine(CachePath, "zips") : destinationDir; bool createZipDirectory = !Directory.Exists(zipDir); if (createZipDirectory) { Directory.CreateDirectory(zipDir); } string file = Path.Combine(zipDir, !uri.IsFile ? hash + ".zip" : Path.GetFileName(uri.AbsolutePath)); if (!File.Exists(file) || !IsValidDownload(file, sha1)) { int progress = -1; DownloadProgressChangedEventHandler downloadHandler = (o, e) => { if (e.ProgressPercentage % 10 != 0 || progress == e.ProgressPercentage) { return; } progress = e.ProgressPercentage; LogMessage("\t({0}/{1}b), total {2:F1}%", e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage); }; using (var client = new System.Net.WebClient()) { client.DownloadProgressChanged += downloadHandler; LogMessage(" Downloading {0} into {1}", url, zipDir); try { client.DownloadFileTaskAsync(url, file).Wait(Token); LogMessage(" Downloading Complete"); } catch (Exception e) { LogCodedError("XA5208", "Download failed. Please download {0} and put it to the {1} directory.", url, destinationDir); LogCodedError("XA5208", "Reason: {0}", e.GetBaseException().Message); Log.LogMessage(MessageImportance.Low, e.ToString()); if (File.Exists(file)) { File.Delete(file); } } client.DownloadProgressChanged -= downloadHandler; } } else { LogDebugMessage(" reusing existing archive: {0}", file); } string contentDir = Path.Combine(destinationDir, "content"); int attempt = 0; while (attempt < 3 && !Log.HasLoggedErrors) { var success = ExtractArchive(url, file, contentDir); if (!success && Log.HasLoggedErrors) { break; } if (!string.IsNullOrEmpty(embeddedArchive)) { string embeddedDir = Path.Combine(destinationDir, "embedded"); success = ExtractArchive(string.Format("{0}:{1}", url, embeddedArchive), Path.Combine(contentDir, embeddedArchive), embeddedDir); if (success) { contentDir = embeddedDir; break; } if (Log.HasLoggedErrors) { break; } if (!success) { Log.LogWarning("Expected File {0} does not exist. Trying to extract again.", Path.Combine(contentDir, embeddedArchive)); if (Directory.Exists(contentDir)) { Directory.Delete(contentDir, recursive: true); } } } else { break; } attempt++; } if (string.IsNullOrEmpty(contentDir) || !Directory.Exists(contentDir)) { if (createZipDirectory) { Directory.Delete(zipDir); } if (createDestinationDirectory) { Directory.Delete(destinationDir); } } return(contentDir); }