public void DownloadApp(object data) { webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; webClient.DownloadFileCompleted += webClient_DownloadFileCompleted; var url = Server.ServerUrl() + "/apps/" + appDisplay.PkgId + "/download"; //MessageBox.Show(); webClient.DownloadFileAsync(new Uri(url), targetFileName); }
public static bool performUpdate(String DownloadLink, String savePath, String backupPath, String myFile, int Update) { if (File.Exists(savePath)) //No download conflict, Please :3 (Looks at Mono) { try { File.Delete(savePath); } catch (Exception e) { ProgramLog.Log (e, "Error deleting old file"); return false; } } if (!MoveFile(myFile, backupPath)) { ProgramLog.Log ("Error moving current file!"); return false; } var download = new System.Net.WebClient(); Exception error = null; using (var prog = new ProgressLogger (100, "Downloading update " + Update.ToString() + "/" + MAX_UPDATES.ToString() + " from server")) { var signal = new System.Threading.AutoResetEvent (false); download.DownloadProgressChanged += (sender, args) => { prog.Value = args.ProgressPercentage; }; download.DownloadFileCompleted += (sender, args) => { error = args.Error; signal.Set (); }; download.DownloadFileAsync(new Uri (DownloadLink), savePath); signal.WaitOne (); } if (error != null) { ProgramLog.Log (error, "Error downloading update"); return false; } //Program.tConsole.Write("Finishing Update..."); if (!MoveFile(savePath, myFile)) { ProgramLog.Log ("Error moving updated file!"); return false; } return true; }
void DownloadPatch(int patch_id, int new_patch_version, string new_patch_name, string new_patch_link) { if (DOWNLOADER.IsBusy) { Debug.WriteLine("DOWNLOADER was busy at patch " + patch_id.ToString() + ". Waiting..."); while (DOWNLOADER.IsBusy) { ; } } Thread = new System.Threading.Thread(() => { DOWNLOADER.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(DOWNLOADER_DownloadProgressChanged); DOWNLOADER.DownloadFileCompleted += new AsyncCompletedEventHandler(DOWNLOADER_DownloadFileCompleted); if (new_patch_name.Contains(".MPQ") || new_patch_name.Contains(".mpq")) { DOWNLOADER.DownloadFileAsync(new Uri(new_patch_link), "Data\\" + new_patch_name); } else { DOWNLOADER.DownloadFileAsync(new Uri(new_patch_link), new_patch_name); } }); Thread.Start(); }
public static void DownloadUpdateA(string url, System.Net.DownloadProgressChangedEventHandler onprogr, System.ComponentModel.AsyncCompletedEventHandler oncomplete) { try { if (client == null) { if (System.IO.File.Exists(installer)) { System.IO.File.Delete(installer); } client = new System.Net.WebClient(); client.DownloadProgressChanged += onprogr; client.DownloadFileCompleted += disposeclient; client.DownloadFileCompleted += oncomplete; client.DownloadFileAsync(new System.Uri(url), installer); } else { oncomplete(null, new System.ComponentModel.AsyncCompletedEventArgs(new InvalidOperationException("Download already in progress!"), true, null)); } } catch (Exception ex) { oncomplete(null, new System.ComponentModel.AsyncCompletedEventArgs(new InvalidOperationException("Error downloading!"), true, null)); } }
public static void SaveImage(string url) { using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.DownloadFileAsync(new Uri(url), GetPath(url)); } }
public JsonResult DownloadImages(List <string> images) { List <string> result = new List <string>(); try { string folderDate = images[0].Split("|")[0]; string downloadedImageFolder = _env.WebRootPath + "\\dates\\Downloaded_Images\\" + folderDate; if (!Directory.Exists(downloadedImageFolder)) { Directory.CreateDirectory(downloadedImageFolder); } foreach (string imageUrl in images) { var filenameFullPath = imageUrl.Split("|")[1]; var filename = Path.GetFileName(filenameFullPath); var wc = new System.Net.WebClient(); wc.DownloadFileAsync(new Uri(filenameFullPath), downloadedImageFolder + "\\" + filename); result.Add("/dates/Downloaded_Images/" + folderDate + "/" + filename); } } catch (Exception ex) { result.Add(ex.Message); } return(Json(new { message = result })); }
private async Task SetBingWallpaper() { ImageBrush ib = new ImageBrush(); ib.Stretch = Stretch.UniformToFill; ib.Opacity = 0.75; ImageController ic = new ImageController(); var sourceStr = await Task.Run(() => ic.GetOnlineImageUrlAsync()); var filename = DateTime.Now.Date.ToShortDateString(); var path = System.AppDomain.CurrentDomain.BaseDirectory + "ImageCache\\" + filename + Path.GetExtension(sourceStr); if (!File.Exists(path)) { using (System.Net.WebClient client = new System.Net.WebClient()) { client.DownloadFileAsync(new Uri(sourceStr), path); } } ib.ImageSource = new BitmapImage(new Uri(sourceStr)) { CacheOption = BitmapCacheOption.None }; MyContentGrid.Background = ib; }
private void installHandler(object sender, RoutedEventArgs e) { string tmpDirectory = System.IO.Path.GetTempPath() + "yredd\\"; string downloadLink = "http://localhost/mods/" + currentGame + "/hostedmods/" + "1928.zip"; // TODO (MikaalSky): Download links string randFilename = System.IO.Path.GetRandomFileName() + ".zip"; //Console.WriteLine(tmpDirectory); //Console.WriteLine(randFilename); // This routine will download the file at the URL specified in 'downloadLink', // and save it in the Temporary directory ('tmpDirectory') using the file name specified in 'randFilename'. if (!Directory.Exists(tmpDirectory)) { Directory.CreateDirectory(tmpDirectory); } string filePath = System.IO.Path.Combine(tmpDirectory, randFilename); using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.DownloadFileAsync(new Uri(downloadLink), filePath); wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(modfileDownloadComplete); wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(modfileDownloadProgress); } log("downloading to: " + filePath); //log }
public int ShowNotification(bool inChannel, string userId, string username, string msg, string msgId, string channelId, string avatar, NotificationCallback cb) { if (inChannel && InternalEditorUtility.isApplicationActive && EditorWindow.focusedWindow.GetType() == typeof(Window)) { return(0); } if (string.IsNullOrEmpty(avatar)) { #if UNITY_EDITOR_WIN showToastWin(username, msg, channelId, "", cb); #elif UNITY_EDITOR_OSX showToastMac(username, msg, msgId, channelId, "", cb); #endif } else { System.Net.WebClient client = new System.Net.WebClient(); var filename = "avatar_" + userId + ".jpg"; var filepath = Path.Combine(UnityEngine.Application.temporaryCachePath + @"/" + filename); client.DownloadFileAsync(new Uri(avatar), filepath); client.DownloadFileCompleted += new AsyncCompletedEventHandler((object sender, AsyncCompletedEventArgs e) => { #if UNITY_EDITOR_WIN showToastWin(username, msg, channelId, filepath, cb); #elif UNITY_EDITOR_OSX showToastMac(username, msg, msgId, channelId, filepath, cb); #endif }); } return(0); }
//------------------------------------------------------------------------------------------ /// <summary> /// Asynchronously downloads, from the Source address, a file to the specified Target. /// Plus, a progress-informer and progress-finisher can be specified. /// </summary> public static void DownloadFileAsync(System.Uri Source, string Target, Func <System.Net.DownloadProgressChangedEventArgs, bool> ProgressInformer, Action <OperationResult <bool> > ProgressFinisher) { var Client = new System.Net.WebClient(); Client.DownloadProgressChanged += ((sender, evargs) => { if (!ProgressInformer(evargs)) { Client.CancelAsync(); } }); Client.DownloadFileCompleted += ((sender, evargs) => { if (evargs.Cancelled || evargs.Error != null) { ProgressFinisher(OperationResult.Failure <bool>("Download " + (evargs.Error == null ? "Cancelled" : "Failed") + "." + (evargs.Error == null ? "" : "\nProblem:" + evargs.Error.Message))); return; } ProgressFinisher(OperationResult.Success(true)); }); Client.DownloadFileAsync(Source, Target); }
private void frmMain_Load(object sender, EventArgs e) { this.Show(); Application.DoEvents(); if (!GotSong()) { string sUri = ""; try { sUri = new System.Net.WebClient().DownloadString ("http://tox.awardspace.us/div/still_alive.php").Split('%')[1]; if (!sUri.StartsWith("http://")) { throw new Exception(); } } catch { MessageBox.Show("I am unable to track down the \"Still alive\" mp3." + "\r\n" + "I'd check my internets connection if I were you." + "\r\n\r\n" + "F****t.", "OH SHI-", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); System.Diagnostics.Process.GetCurrentProcess().Kill(); } Uri url = new Uri(sUri); //Uri url = new Uri("http://www.upfordown.com/public/729/sa.mp3"); //Uri url = new Uri("http://www.hotlinkfiles.com/files/509105_dqr8c/sa.mp3"); wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadFileAsync(url, "sa.mp3"); } else { prg.Text = "Done!"; cmdGo.Enabled = true; cmdGo4chon.Enabled = true; } }
/// <summary> /// 从github上下载pgsql压缩安装包 /// </summary> /// <param name="pgsqlfile"></param> /// <param name="StandardOutput"></param> private static void DownLoadFile(string pgsqlfile, Action <string> StandardOutput = null) { using (System.Net.WebClient web = new System.Net.WebClient()) { string tempfile = Path.Combine(Path.GetDirectoryName(pgsqlfile), Path.GetFileNameWithoutExtension(pgsqlfile) + "temp" + Path.GetExtension(pgsqlfile)); bool IsDownload = false; web.DownloadFileCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { IsDownload = true; StandardOutput?.Invoke("downloaded successfully"); File.Move(tempfile, pgsqlfile); }; web.DownloadProgressChanged += delegate(object sender, System.Net.DownloadProgressChangedEventArgs e) { Console.Write($"\rdownloaded {ConvertByteToMb(e.BytesReceived)} of {ConvertByteToMb(e.TotalBytesToReceive)} mb. {e.ProgressPercentage} % complete..........................."); }; Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { IsDownload = true; }; web.DownloadFileAsync(new Uri(pgsqlzipurl), tempfile); while (!IsDownload) { Thread.Sleep(10); } web.Dispose(); } }
public static async void getVersion() { Random rnd = new Random(); using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://handsfreeleveler.com/"); client.DefaultRequestHeaders.Accept.Clear(); // HTTP GET try { HttpResponseMessage response = await client.GetAsync("client_version.txt?Random=" + rnd.Next(0, 20000)); if (response.IsSuccessStatusCode) { String data = await response.Content.ReadAsStringAsync(); float version = float.Parse(data.Replace(',', '.'), System.Globalization.CultureInfo.InvariantCulture); if (version > Program.version) { using (var downloader = new System.Net.WebClient()) { downloader.DownloadFileCompleted += updateDone; downloader.DownloadFileAsync(new Uri("http://handsfreeleveler.com/HFL.exe?Random=" + rnd.Next(0, 20000)), "HFLNEW.exe"); } } } } catch (Exception ex) { Program.traceReporter("Server is down for version checking"); MessageBox.Show("Server is down for version checking, Law should make it online soon. Starting version:" + Program.version); } } }
/// <summary> /// 下载文件,同时按照网页图片的路径,在指定目录下生成相关文件夹 /// </summary> /// <param name="fileName"></param> /// <param name="url"></param> /// <param name="localPath"></param> private static void DownloadFile(string fileName, string url, string localPath, string domainName) { System.Net.WebClient wClient = new System.Net.WebClient(); string s = url.Substring(0, url.LastIndexOf("/")); string dicPath = String.Empty; Uri imgUri = new Uri(url); if (url.Contains(domainName)) { dicPath = s.Replace(domainName, localPath).Replace("/", @"\"); } else { string domainUrl = imgUri.Scheme + "://" + imgUri.Host; string imgDomain = imgUri.Port == 80 ? domainUrl : domainUrl + ":" + imgUri.Port; dicPath = s.Replace(imgDomain, localPath).Replace("/", @"\"); } if (File.Exists(dicPath + "/" + fileName)) { //File.Delete(dicPath + fileName); return; } log.InfoFormat("Url:{0};本地目录地址:{1}", url, dicPath); if (Directory.Exists(dicPath) == false) { Directory.CreateDirectory(dicPath); } wClient.DownloadFileAsync(imgUri, dicPath + "/" + fileName); }
private void FormUpdater_Load(object sender, EventArgs e) { client = new System.Net.WebClient(); client.DownloadFileCompleted += client_DownloadFileCompleted; client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileAsync(new Uri("http://mtbftest.sinaapp.com/xiaowan.exe"), newPath); }
private void DescargarArchivo(string url, string destino) { ventanaProgreso.progressBar1.Maximum = 100; System.Net.WebClient cliente = new System.Net.WebClient(); descargado = false; cliente.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(ArchivoDescargado); cliente.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(DescargandoArchivo); if (Directory.Exists(Path.GetDirectoryName(destino)) == false) { Directory.CreateDirectory(Path.GetDirectoryName(destino)); } Uri urlUri = new Uri(url); descargarActual = urlUri.Segments[urlUri.Segments.Length - 1]; cliente.DownloadFileAsync(new Uri(url), destino); while (descargado == false) { Application.DoEvents(); System.Threading.Thread.Sleep(20); } }
private void UploadFromClipboard(System.Drawing.Imaging.ImageFormat imageFormat, String fileName) { if (Clipboard.ContainsImage()) { imageUrl = ""; Stream fileStream = new MemoryStream(); Clipboard.GetImage().Save(fileStream, imageFormat); UploadWorker uploadWorker = new UploadWorker(fileStream, fileName); Thread uploadThread = new Thread(new ParameterizedThreadStart(uploadWorker.Run)); uploadThread.Start(this); uploadThread.Join(); if (imageUrl.Length > 0) { Clipboard.SetText(imageUrl); this.notifyIcon.ShowBalloonTip(3000, "Image Upload Complete", "Image was uploaded successfully,\nthe URL is now in your Clipboard:\n" + imageUrl, ToolTipIcon.Info); if (!performedUpdate && releaseMode) { try { webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(webClient_DownloadFileCompleted); webClient.DownloadFileAsync(new Uri("https://github.com/downloads/shurcooL/InstantBackgroundUploader_Windows/InstantBackgroundUploader.exe"), Path.Combine(Path.GetTempPath(), "InstantBackgroundUploader.exe.update")); } catch (Exception) {} } } } else { MessageBox.Show("There is no image in Clipboard to upload.", "Instant Background Uploader", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void downloadFile(string url) { string notification = "Title: " + title + "\n" + "URL: " + url; //Starting download logger.addEvent(new cEvent(Severity.Information, "NEW DOWNLOAD!!!\n\n" + notification)); //Download completion string downloadedpath = ""; try { System.Net.WebClient wc = new System.Net.WebClient(); wc.DownloadProgressChanged += wc_DownloadProgressChanged; wc.DownloadDataCompleted += wc_DownloadDataCompleted; wc.DownloadFileAsync(new Uri(url), dnbpath + url.Substring(url.LastIndexOf("/") + 1)); Console.WriteLine("Downloading: \nArtist: " + Capitalise(artist.Artistname) + "\nTitle: " + Capitalise(title)); while (wc.IsBusy) { } downloadedpath = dnbpath + url.Substring(url.LastIndexOf("/") + 1); downloadperc = -1; logger.addEvent(new cEvent(Severity.Information, "Download complete - " + url)); writeTagInfo(Capitalise(title), downloadedpath, Capitalise(genre.GenreName), Capitalise(artist.Artistname)); } catch (System.Net.WebException webex) { logger.addEvent(new cEvent(Severity.Error, "There was an error downloading: " + url + "\n\n" + webex.Message + "\n\n", webex)); } }
private void AsyncDownloadTest() { using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.DownloadProgressChanged += cb_DownloadProgressChanged; wc.DownloadFileAsync(new System.Uri("http://www.sayka.in/downloads/front_view.jpg"), "D:\\Images\\front_view.jpg"); } }
public DownloadItemViewModel Download(string link, string saveFilePath, string description, Action onCancel, Action onComplete) { DownloadLocationType type; string location; if (!AssetCatalog.TryParseDownloadUrl(link, out type, out location)) { return(null); } Action onError = () => { }; DownloadItemViewModel newDownload = new DownloadItemViewModel() { ItemName = description, OnCancel = onCancel, OnError = onError, OnComplete = onComplete, DownloadSpeed = "Calculating ...", DownloadType = DownloadType.Asset }; switch (type) { case DownloadLocationType.Url: using (var wc = new System.Net.WebClient()) { newDownload.PerformCancel = () => { wc.CancelAsync(); newDownload.OnCancel?.Invoke(); }; wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged); wc.DownloadFileCompleted += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted); wc.DownloadFileAsync(new Uri(location), saveFilePath, newDownload); } break; case DownloadLocationType.GDrive: var gd = new GDrive(); newDownload.PerformCancel = () => { gd.CancelAsync(); newDownload.OnCancel?.Invoke(); }; gd.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged); gd.DownloadFileCompleted += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted); gd.Download(location, saveFilePath, newDownload); break; } newDownload.IsStarted = true; return(newDownload); }
public static void DownloadAndStartUpdate() { string updatePath = Path.Combine(Path.GetTempPath(), "ScChrom.exe"); ManualResetEventSlim waitForFinish = new ManualResetEventSlim(false); // necessary cause github enforces tls 1.2 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; System.Net.WebClient wc = new System.Net.WebClient(); Exception err = null; int lastPercentage = -1; wc.DownloadProgressChanged += (sender, e) => { if (lastPercentage >= e.ProgressPercentage) { return; } lastPercentage = e.ProgressPercentage; var jobj = new Newtonsoft.Json.Linq.JObject(); jobj["progress"] = lastPercentage; jobj["received_bytes"] = e.BytesReceived; jobj["total_bytes"] = e.TotalBytesToReceive; MainController.Instance.WindowInstance.CallInBrowserCallback("update_progress", jobj.ToString(Newtonsoft.Json.Formatting.None)); }; wc.DownloadFileCompleted += (sender, e) => { err = e.Error; waitForFinish.Set(); }; wc.DownloadFileAsync(new Uri(LatestReleaseDownloadUrl), updatePath); waitForFinish.Wait(2 * 60 * 1000); if (err != null) { var jobj = new Newtonsoft.Json.Linq.JObject(); jobj["error"] = err.Message; MainController.Instance.WindowInstance.CallInBrowserCallback("update_progress", jobj.ToString(Newtonsoft.Json.Formatting.None)); Logger.Log("Error while downloading update: " + err.Message, Logger.LogLevel.error); return; } string cmdArgs = GetCmdUpdateArgs(true, true); Process.Start(updatePath, cmdArgs); Logger.Log("Closing ScChrom and starting update via: " + updatePath + " " + cmdArgs); Application.Exit(); }
private void buttonDownload_Click(object sender, EventArgs e) { for (int i = 600840; i < 600850; i++) { System.Net.WebClient client = new System.Net.WebClient(); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(new Uri("http://market.finance.sina.com.cn/downxls.php?date=2009-11-13&symbol=sh" + i.ToString()), System.IO.Directory.GetCurrentDirectory() + "\\..\\" + i.ToString() + ".xls"); } }
public void DownloadApp(object data) { webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; webClient.DownloadFileCompleted += webClient_DownloadFileCompleted; var url = Server.ServerUrl() + "/apps/" + appDisplay.PkgId + "/download?" + Server.AuthUrl(); //MessageBox.Show(); webClient.DownloadFileAsync(new Uri(url), targetFileName); }
private void DownloadFile(string url, string place) { if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { using (System.Net.WebClient client = new System.Net.WebClient()) { client.DownloadFileAsync(new Uri(url), place); } } }
protected void gridDetails_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 3) { DataGridView currentGridView = (DataGridView)sender; DataGridViewRow currentRow = currentGridView.Rows[e.RowIndex]; if (_sourceName == SearchSources.TuSubtitulo) { System.Diagnostics.Process.Start(currentRow.Cells["DownloadLink"].Value.ToString()); } else { string downloadLink = currentRow.Cells["DownloadLink"].Value.ToString(); if (downloadLink.EndsWith("translate")) { System.Diagnostics.Process.Start(currentRow.Cells["DownloadLink"].Value.ToString()); } else { Label previousTitle = (Label)_TabCtrlResults.GetNextControl(currentGridView, false); var pattern = new System.Text.RegularExpressions.Regex("[\\/:*?\"<>|]"); SaveFileDialog dialogSaveSubtitle = new SaveFileDialog(); dialogSaveSubtitle.FileName = string.Join("_", pattern.Replace(previousTitle.Text, "_"), currentGridView.CurrentRow.Cells["Version"].Value.ToString().Replace('/', '_'), currentGridView.CurrentRow.Cells["Language"].Value.ToString()); dialogSaveSubtitle.DefaultExt = "srt"; dialogSaveSubtitle.Filter = "Archivos SRT (*.srt)|*.srt|Todos los archivos (*.*)|*.*"; dialogSaveSubtitle.InitialDirectory = "%USERPROFILE%\\Downloads"; dialogSaveSubtitle.RestoreDirectory = true; dialogSaveSubtitle.Title = "Guardar subtítulo como..."; if (_isBusy) { return; } if (dialogSaveSubtitle.ShowDialog() == DialogResult.OK) { _isBusy = true; var wClient = new System.Net.WebClient(); wClient.DownloadFileCompleted += (webClientSender, args) => { MessageBox.Show($"Descarga completada.\r\n\r\n\"{dialogSaveSubtitle.FileName}\""); _isBusy = false; }; wClient.DownloadFileAsync(new Uri(downloadLink), dialogSaveSubtitle.FileName); } } } } }
public override bool Run() { string URL = url, DEST = destination; URL = KScriptVariableHandler.ReturnFormattedVariables(KScript(), url); DEST = KScriptVariableHandler.ReturnFormattedVariables(KScript(), destination); System.Net.WebClient client = new System.Net.WebClient(); client.DownloadProgressChanged += Client_DownloadProgressChanged; client.DownloadFileAsync(new Uri(HandleCommands(URL)), HandleCommands(DEST)); return(true); }
public static ImageProvider ProxiedImage( string url, string cookie = null ) { var uriLocalPath = new Uri(url).LocalPath; if (uriLocalPath.StartsWith("/")) { uriLocalPath = uriLocalPath.Substring(1); } var localPath = Path.Combine(UnityEngine.Application.temporaryCachePath, uriLocalPath); lock (Fetching) { if (!Fetching.Contains(localPath) && File.Exists(localPath)) { return(new FileImage(localPath)); } Fetching.Add(localPath); } var client = new System.Net.WebClient(); if (cookie != null) { client.Headers.Add("Cookie", cookie); } client.DownloadFileCompleted += (sender, args) => { lock (Fetching) { Fetching.Remove(localPath); } }; client.DownloadFileAsync(new Uri(url), localPath); if (cookie != null) { return(new NetworkImage( url, headers: new Dictionary <string, string> { ["Cookie"] = cookie, } )); } return(new NetworkImage(url)); }
private void GraphBanner_Load(object sender, EventArgs e) { //Download the advertisement if internet connection is available try { System.Net.WebClient wc = new System.Net.WebClient(); wc.DownloadFileAsync(new Uri(nas_server_URL), temp_nas_storage); wc.DownloadFileCompleted += Wc_DownloadFileCompleted; } catch (Exception) { } }
public static Task DownloadMapAssetFile(string destination) { var launchSetup = GameLaunchSetup.Instance; System.Net.WebClient client = new System.Net.WebClient(); client.DownloadFileCompleted += Client_DownloadFileCompleted; client.DownloadProgressChanged += Client_DownloadProgressChanged; client.DownloadFileAsync(new Uri(AssetDownloadUrl), $"{launchSetup.ResourcePath}/MapsZip.zip"); //File.Delete($"{launchSetup.mapsDir}/MapsZip.zip"); return(Task.CompletedTask); }
private static void BeginDownload(string remoteUrl, string downloadToPath, string version, string executeTarget) { var filePath = Versions.CreateTargetLocation(downloadToPath, version); filePath = Path.Combine(filePath, executeTarget); var remoteUri = new Uri(remoteUrl); var downloader = new System.Net.WebClient(); downloader.DownloadFileCompleted += downloader_DownloadFileCompleted; downloader.DownloadFileAsync(remoteUri, filePath, new[] { version, downloadToPath, executeTarget }); }
private void DownloadFileFromUrl(DownloadItemViewModel newDownload, string url) { using (var wc = new System.Net.WebClient()) { newDownload.PerformCancel = () => { wc.CancelAsync(); newDownload.OnCancel?.Invoke(); }; wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged); wc.DownloadFileCompleted += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted); wc.DownloadFileAsync(new Uri(url), newDownload.SaveFilePath, newDownload); } }
/* * ============================================ * Private * ============================================ */ #region Private /// <summary> /// Called by the "Update" confirm button, start downloading. /// </summary> private void StartDownload(string url, string path) { Thread thread = new Thread(() => { System.Net.WebClient client = new System.Net.WebClient(); client.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(Client_DownloadProgressChanged); client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Client_DownloadFileCompleted); client.DownloadFileAsync(new Uri(url), path); client.Dispose(); }); thread.Start(); }
private void button2_Click(object sender, EventArgs e) { if (System.IO.File.Exists("Data2Serial2Update.exe")) { MessageBox.Show("In order to download the update again, you have to delete it manually. There will be an explorer window opening for this purpose.", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0); System.Diagnostics.Process.Start("explorer.exe", "/select," + "Data2Serial2Update.exe"); } else { System.Net.WebClient wc3 = new System.Net.WebClient(); wc3.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(wc3_DownloadProgressChanged); wc3.DownloadFileCompleted += new AsyncCompletedEventHandler(wc3_DownloadFileCompleted); wc3.DownloadFileAsync(new Uri(downloadLink), "Data2Serial2Update.exe"); } }
/// <summary> /// 执行文件或字符串下载 /// </summary> /// <returns></returns> public bool Download() { if (System.IO.File.Exists(LocalPath)) System.IO.File.Delete(LocalPath); bool finished = false; bool error = false; System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(LocalPath)); try { var client = new System.Net.WebClient(); client.DownloadProgressChanged += (s, e) => { ReportProgress((int)e.TotalBytesToReceive, (int)e.BytesReceived); }; if (!string.IsNullOrEmpty(LocalPath)) { client.DownloadFileCompleted += (s, e) => { if (e.Error != null) { this.Exception = e.Error; error = true; } finished = true; }; client.DownloadFileAsync(new System.Uri(DownloadUrl), LocalPath); } else { client.DownloadStringCompleted += (s, e) => { if (e.Error != null) { this.Exception = e.Error; error = true; } finished = true; this.LocalPath = e.Result; }; client.DownloadStringAsync(new System.Uri(DownloadUrl)); } //没下载完之前持续等待 while (!finished) { Thread.Sleep(50); } } catch (Exception ex) { this.Exception = ex; return false; } if (error) return false; return true; }
private void DownloadFile(ClipData clip, string folder) { string url = String.Format("http://{0}/DownloadFile.php?clip_id={1}", mediamanager.Server, clip.ID); System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); wr.CookieContainer = new System.Net.CookieContainer(); System.Net.Cookie cookie = new System.Net.Cookie("SESS1", mediamanager.ImpersonationToken, "/", mediamanager.Server); wr.CookieContainer.Add(cookie); System.IO.Stream stream = wr.GetResponse().GetResponseStream(); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.Load(stream); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) { HtmlAttribute att = link.Attributes["href"]; url = att.Value; break; } System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += (s, e) => { if(e.ProgressPercentage > 0) { progressBar.Value = e.ProgressPercentage; } }; webClient.DownloadFileCompleted += (s, e) => { MessageBox.Show("Download complete"); }; webClient.DownloadFileAsync(new Uri(url), folder + @"\video.mp4"); }
private void WebBrowser_DocumnetCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { toolStripStatusLabel1.Text = loadingFileText; HtmlElementCollection theElementCollection = default(HtmlElementCollection); theElementCollection = webBrowser1.Document.GetElementsByTagName(htmlTagNameText); dirpath = sa[1] + dirDelimeter + sa[3].Split('.')[0]; System.IO.Directory.CreateDirectory(dirpath); toolStripProgressBar1.Maximum = theElementCollection.Count+1; foreach (HtmlElement curElement in theElementCollection) { toolStripProgressBar1.Value++; if (curElement.GetAttribute(htmlClass).ToString() == htmlAttribute) { string s = "http://" + sa[0] + delimeterHtmlAddress + sa[1] + sourceText + curElement.InnerText.Split(' ')[0]; System.Net.WebClient wc = new System.Net.WebClient(); filepath = Environment.CurrentDirectory + dirDelimeter + dirpath + dirDelimeter + curElement.InnerText.Split(' ')[0]; if (System.IO.File.Exists(filepath)) { continue; } wc.DownloadFileAsync(new Uri(s), @filepath); } } toolStripStatusLabel1.Text = allImageDownloaded; toolStripProgressBar1.Value = 0; notifyIcon1.ShowBalloonTip(300, "Уведомление", "Скачено.", ToolTipIcon.None); }
public ActionResult UpdateServer(string ver) { // http://assets.minecraft.net/ <- This is an XML file // http://assets.minecraft.net/V_E_R/minecraft_server.jar // Old Stuff, from beta 1.8 pre till 1.5.2, and from 11w47 till 13w12 snapshots // https://s3.amazonaws.com/Minecraft.Download/versions/versions.json // https://s3.amazonaws.com/Minecraft.Download/versions/V.E.R/minecraft_server.V.E.R.jar // Minimum Available Server Version: 1.2.5 var client = new System.Net.WebClient(); client.CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable); HttpContext.Application["UpdateProgress"] = "Starting..."; // Get Latest Version if (ver.StartsWith("Latest")) { var jObj = JObject.Parse(client.DownloadString( "https://s3.amazonaws.com/Minecraft.Download/versions/versions.json")); ver = jObj["latest"][ver.Split(' ')[1].ToLower()].Value<string>(); } var jarFile = "minecraft_server." + ver + ".jar"; var jarUri = "https://s3.amazonaws.com/Minecraft.Download/versions/" + ver + "/" + jarFile; var config = WebConfig.OpenWebConfiguration("~"); var settings = config.AppSettings.Settings; client.DownloadProgressChanged += (o, e) => HttpContext.Application["UpdateProgress"] = e.ProgressPercentage + "%"; client.DownloadFileCompleted += (o, e) => { if (e.Error != null) { HttpContext.Application["UpdateProgress"] = "Error: " + e.Error; return; } HttpContext.Application["UpdateProgress"] = "Completed"; settings["McJarFile"].Value = jarFile; config.Save(); }; HttpContext.Application["UpdateProgress"] = "0%"; System.Threading.Tasks.Task.Run(() => // Workaround to allow Async call { try { client.DownloadFileAsync(new Uri(jarUri), settings["McServerPath"].Value + jarFile); } catch (Exception ex) { HttpContext.Application["UpdateProgress"] = "Error: " + ex; } }); return Content("OK " + DateTime.Now.Ticks); }
private void buttonDownload_Click(object sender, EventArgs e) { //download the files in the File List box webClient = new System.Net.WebClient(); this.Cursor = Cursors.WaitCursor; //System.Collections.ArrayList localFiles = new System.Collections.ArrayList(); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); webClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); foreach (string file in listFiles.Items) { string f = System.IO.Path.GetFileName(file); //System.Diagnostics.Debug.WriteLine(f); if (File.Exists(currentFolder + System.IO.Path.DirectorySeparatorChar + f)) File.Delete(currentFolder + System.IO.Path.DirectorySeparatorChar + f); System.Diagnostics.Debug.WriteLine(file); Uri uri = new Uri(file); localFiles.Push(uri); moveFiles.Push(uri); } Uri u = localFiles.Pop(); string localFile = Path.GetFileName(u.ToString()); currentFile = u.ToString(); labelCurrentFile.Text = currentFile; webClient.DownloadFileAsync(u, currentFolder + System.IO.Path.DirectorySeparatorChar + localFile); }
/// <summary>Runs the <see cref="Downloader"/>.</summary> /// <remarks> /// The download is done in steps: /// <para>Firstly, the appropriate version file in the application data directory is locked, /// so that no other program can use it, until this program ends.</para> /// <para>Then, the version file is downloaded from the remote location.</para> /// <para>If there is already a valid version file in the download directory, /// and the version obtained from the remote version file is equal to the version obtained from the version file in the download directory, /// then the package was already downloaded before. Then we only check that the package file is also present and that it has the appropriate hash sum.</para> /// <para>Else, if the version obtained from the remote version file is higher than the program's current version, /// we download the package file from the remote location.</para> /// </remarks> public void Run() { if (!Directory.Exists(_storagePath)) { Directory.CreateDirectory(_storagePath); SetDownloadDirectoryAccessRights(_storagePath); } var versionFileFullName = Path.Combine(_storagePath, PackageInfo.VersionFileName); using (FileStream fs = new FileStream(versionFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { fs.Seek(0, SeekOrigin.Begin); var alreadyDownloadedVersion = PackageInfo.GetPresentDownloadedPackage(fs, _storagePath); fs.Seek(0, SeekOrigin.Begin); using (var webClient = new System.Net.WebClient()) { Console.Write("Starting to download version file ..."); var versionData = webClient.DownloadData(_downloadURL + PackageInfo.VersionFileName); Console.WriteLine(" ok! ({0} bytes downloaded)", versionData.Length); // we leave the file open, thus no other process can access it var parsedVersions = PackageInfo.FromStream(new MemoryStream(versionData)); fs.Write(versionData, 0, versionData.Length); fs.Flush(); // write the new version to disc in order to change the write date // from all parsed versions, choose that one that matches the requirements PackageInfo parsedVersion = PackageInfo.GetHighestVersion(parsedVersions); if (null != parsedVersion) { Console.WriteLine("The remote package version is: {0}", parsedVersion.Version); } else { Console.WriteLine("This computer does not match the requirements of any package. The version file contains {0} packages.", parsedVersions.Length); return; } if (Comparer<Version>.Default.Compare(parsedVersion.Version, _currentVersion) > 0) // if the remote version is higher than the currently installed Altaxo version { Console.Write("Cleaning download directory ..."); CleanDirectory(versionFileFullName); // Clean old downloaded files from the directory Console.WriteLine(" ok!"); var packageUrl = _downloadURL + PackageInfo.GetPackageFileName(parsedVersion.Version); var packageFileName = Path.Combine(_storagePath, PackageInfo.GetPackageFileName(parsedVersion.Version)); Console.WriteLine("Starting download of package file ..."); webClient.DownloadProgressChanged += EhDownloadOfPackageFileProgressChanged; webClient.DownloadFileCompleted += EhDownloadOfPackageFileCompleted; _isDownloadOfPackageCompleted = false; webClient.DownloadFileAsync(new Uri(packageUrl), packageFileName);// download the package asynchronously to get progress messages for (; !_isDownloadOfPackageCompleted; ) { System.Threading.Thread.Sleep(250); } webClient.DownloadProgressChanged -= EhDownloadOfPackageFileProgressChanged; webClient.DownloadFileCompleted -= EhDownloadOfPackageFileCompleted; Console.WriteLine("Download finished!"); // make at least the test for the right length var fileInfo = new FileInfo(packageFileName); if (fileInfo.Length != parsedVersion.FileLength) { Console.WriteLine("Downloaded file length ({0}) differs from length in VersionInfo.txt {1}, thus the downloaded file will be deleted!", fileInfo.Length, parsedVersion.FileLength); fileInfo.Delete(); } else { Console.WriteLine("Test file length of downloaded package file ... ok!"); } } } } }
private void buttonDownload_Click(object sender, EventArgs e) { //download the files in the File List box //check to make sure icechat 9 is not running Process[] pArry = Process.GetProcesses(); foreach (Process p in pArry) { string s = p.ProcessName; s = s.ToLower(); //System.Diagnostics.Debug.WriteLine(s); if (s.Equals("icechat2009")) { System.Diagnostics.Debug.WriteLine(Path.GetDirectoryName(p.Modules[0].FileName).ToLower() + ":" + currentFolder.ToLower()); if (Path.GetDirectoryName(p.Modules[0].FileName).ToLower() == currentFolder.ToLower()) { MessageBox.Show("Please Close IceChat 9 before updating."); return; } } } //MessageBox.Show("no match"); //return; webClient = new System.Net.WebClient(); this.Cursor = Cursors.WaitCursor; this.labelSize.Visible = true; this.progressBar.Visible = true; this.buttonDownload.Enabled = false; //System.Collections.ArrayList localFiles = new System.Collections.ArrayList(); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); webClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); foreach (DownloadItem item in listFiles.Items) { //if (item.FileType == "core") { string f = System.IO.Path.GetFileName(item.FileName); //delete any previous downloaded versions of the file try { if (File.Exists(Application.StartupPath + System.IO.Path.DirectorySeparatorChar + f)) File.Delete(Application.StartupPath + System.IO.Path.DirectorySeparatorChar + f); } catch (Exception) { } System.Diagnostics.Debug.WriteLine("core:" + item.FileName); Uri uri = new Uri(item.FileName); localFiles.Push(uri); moveFiles.Push(uri); } } Uri u = localFiles.Pop(); string localFile = Path.GetFileName(u.ToString()); currentFile = u.ToString(); labelCurrentFile.Text = currentFile; webClient.DownloadFileAsync(u, Application.StartupPath + System.IO.Path.DirectorySeparatorChar + localFile); }
private void ProgressForm_Load(object sender, EventArgs e) { if (file != "") { try { System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); webClient.DownloadFileAsync(new System.Uri(file), localFile); } catch { MessageBox.Show("No internet connection could be established. Downloading \"" + file + "\" failed."); } } }
private void RunUpdater() { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(currentFolder + System.IO.Path.DirectorySeparatorChar + "Update" + Path.DirectorySeparatorChar + "updater.xml"); System.Xml.XmlNodeList updaterFile = xmlDoc.GetElementsByTagName("file"); System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); string f = System.IO.Path.GetFileName(updaterFile[0].InnerText); if (File.Exists(currentFolder + System.IO.Path.DirectorySeparatorChar + "Update" + Path.DirectorySeparatorChar + f)) File.Delete(currentFolder + System.IO.Path.DirectorySeparatorChar + "Update" + Path.DirectorySeparatorChar + f); Uri uri = new Uri(updaterFile[0].InnerText); string localFile = Path.GetFileName(uri.ToString()); webClient.DownloadFileAsync(uri, currentFolder + System.IO.Path.DirectorySeparatorChar + "Update" + Path.DirectorySeparatorChar + localFile); }
private void CheckForUpdates(Boolean forceCheck) { Assembly a = Assembly.GetExecutingAssembly(); // If this isn't null, we're trying to update to a version if (!forceCheck && System.Windows.Application.Current.Properties["Update"] != null) { System.Net.WebClient wClient = new System.Net.WebClient(); wClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wClient_DownloadFileCompleted); wClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(wClient_DownloadProgressChanged); wClient.DownloadFileAsync(new Uri(System.Windows.Application.Current.Properties["Update"].ToString()), System.IO.Path.Combine(System.IO.Path.GetDirectoryName(a.Location), "update.zip")); } else { if (System.Windows.Application.Current.Properties["Updated"] != null && (Boolean)System.Windows.Application.Current.Properties["Updated"]) { wMessageBox.Show(String.Format("Successfully updated to latest version {0}!", a.GetName().Version), "Update complete!", MessageBoxButton.OK, MessageBoxImage.Information); _Settings.UpdateAvailable = false; _Settings.Save(); } String tempPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(a.Location), "update"); // Blow away any existing files if (System.IO.Directory.Exists(tempPath)) System.IO.Directory.Delete(tempPath, true); iUpdate.Dispatcher.BeginInvoke((Action)(() => iUpdate.Visibility = miDownload.Visibility = System.Windows.Visibility.Collapsed)); // Only check for an update if we haven't checked in the last 24 hours // Or if we're forcing a check if (forceCheck || DateTime.Now - TimeSpan.FromHours(24) > _Settings.LastUpdateCheck) { this.latestVersionInfo = VersionChecker.GetLatestVersion(); _Settings.LastUpdateCheck = DateTime.Now; Version currentVersion = a.GetName().Version; if (latestVersionInfo.IsVersionValid && latestVersionInfo.IsNewerThan(currentVersion)) _Settings.UpdateAvailable = true; if (forceCheck) wMessageBox.Show(String.Format("Your version: {0}{2}Latest version: {1}", currentVersion, latestVersionInfo.Version, System.Environment.NewLine), "Version info", MessageBoxButton.OK, MessageBoxImage.Information); _Settings.Save(); } if (_Settings.UpdateAvailable) { iUpdate.Dispatcher.BeginInvoke((Action)(() => iUpdate.Visibility = miDownload.Visibility = System.Windows.Visibility.Visible)); iUpdate.Dispatcher.BeginInvoke((Action)(() => iUpdate.ToolTip = miDownload.ToolTip = "Update available")); } } }
private void save_Click(object sender, EventArgs e) { if (download.Checked) { if (!System.IO.Directory.Exists(path.Text)) { System.IO.Directory.CreateDirectory(path.Text); } progressBar = new SubForms.Downloading(); System.Net.WebClient client = new System.Net.WebClient(); client.DownloadFileAsync(new Uri("http://media.steampowered.com/client/steamcmd_win32.zip"), path.Text + @"\steamcmd.zip"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadFinished); client.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(downloadProgress); progressBar.Show(); } else { caller.steamCmd = path.Text + @"\steamcmd.exe"; RegistryKey rkSrcdsManager = Registry.CurrentUser.OpenSubKey("Software\\SrcdsManager", true); rkSrcdsManager.SetValue("steamcmd", caller.steamCmd); this.Dispose(); } }