public CCForm() { InitializeComponent(); string UpdatorApp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Updator\\UpdatorCC.exe"); //odkaz na spoustec minecraftu string remoteUri1 = "http://files.customcraft.cz/"; string fileName1 = "verze.txt", myStringWebResource = null; string misto1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), fileName1); WebClient verze1 = new WebClient(); string App = "AppVerze.txt"; string AppVerze = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), App); WebClient App1 = new WebClient(); string spoustec1 = "AppVerze.txt"; string spoustecweb1 = "Install\\AppVerze.txt"; string spoustec = System.IO.File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), spoustec1)); //verze updatu na webu string spoustecweb = System.IO.File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), spoustecweb1)); //verze klienta if (spoustec == spoustecweb) { //vysere se na vše a pokračuje na CCFORM_Load } else { System.Diagnostics.Process.Start(UpdatorApp); //smaže složku Install a reinstaluje klienta Application.Exit(); } myStringWebResource = remoteUri1 + fileName1; verze1.DownloadFileAsync(new Uri(myStringWebResource), misto1); //stažení verze klienta z webu myStringWebResource = remoteUri1 + fileName1; verze1.DownloadFileAsync(new Uri(myStringWebResource), AppVerze); //Stažení verze spouštěče k aktualizaci }
private void KeppySynthUpdateDL_Load(object sender, EventArgs e) { using (webClient = new WebClient()) { webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); if (test == 0) { URL = new Uri(String.Format("https://github.com/KaleidonKep99/Keppy-s-Synthesizer/releases/download/{0}/KeppysSynthSetup.exe", VersionToDownload)); } else { webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); URL = new Uri(FullURL); } try { if (test == 0) { webClient.DownloadFileAsync(URL, String.Format("{0}KeppySynthSetup.exe", Path.GetTempPath())); } else { string userfolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Keppy's Synthesizer"; webClient.DownloadFileAsync(URL, String.Format("{0}\\{1}", userfolder, FullURL.Split('/').Last())); } } catch { MessageBox.Show("The configurator can not connect to the GitHub servers.\n\nCheck your network connection, or contact your system administrator or network service provider.", "Keppy's Synthesizer - Connection error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
public DownloadLWJGL(MainForm form, String path) { this.form = form; this.path = path; if (File.Exists(path + "natives.zip")) File.Delete(path + "natives.zip"); if (File.Exists(path + "lwjgl.jar")) File.Delete(path + "lwjgl.jar"); if (File.Exists(path + "jinput.jar")) File.Delete(path + "jinput.jar"); if (File.Exists(path + "lwjgl_util.jar")) File.Delete(path + "lwjgl_util.jar"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); native = new Uri(downloadLink + "windows_natives.jar"); lwjgl = new Uri(downloadLink + "lwjgl.jar"); jinput = new Uri(downloadLink + "jinput.jar"); util = new Uri(downloadLink + "lwjgl_util.jar"); WebClient client = new WebClient(); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(form.SetProgressBar); //TODO: Don't use mainForm client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Downloaded); form.SetTask("Downloading Natives"); //TODO: ^ client.DownloadFileAsync(native, path + "natives.zip"); while (isDownloading) { Application.DoEvents(); } isDownloading = true; form.SetTask("Downloading LWJGL"); //TODO: ^ client.DownloadFileAsync(lwjgl, path + "lwjgl.jar"); while (isDownloading) { Application.DoEvents(); } isDownloading = true; form.SetTask("Downloading JInput"); //TODO: ^ client.DownloadFileAsync(jinput, path + "jinput.jar"); while (isDownloading) { Application.DoEvents(); } isDownloading = true; form.SetTask("Downloading LWJGL Util"); //TODO: ^ client.DownloadFileAsync(util, path + "jwjgl_util.jar"); while (isDownloading) { Application.DoEvents(); } }
private void btnDownload_Click(object sender, EventArgs e) { EnableControl(false); if (CheckVariable()) { var downloadsrc = new DownloadSource(textLink.Text); if (downloadsrc.LinkXml != null) { var dir = textDSTdownload.Text; var webClient = new WebClient(); int i = 0; webClient.DownloadFileAsync(new Uri(downloadsrc.ListMusics.DsItems[i].Music.Source), dir + @"\" + downloadsrc.ListMusics.DsItems[i].Music.Title + "." + downloadsrc.ListMusics.DsItems[i].Type); webClient.DownloadProgressChanged += (u, v) => { toolStripLbtitle.Text = string.Format("{0} - {1} %", downloadsrc.ListMusics.DsItems[i].Music.Title, v.ProgressPercentage); }; webClient.DownloadFileCompleted += (u, v) => { if (i < downloadsrc.ListMusics.DsItems.Count - 1) { i++; webClient.DownloadFileAsync(new Uri(downloadsrc.ListMusics.DsItems[i].Music.Source), dir + @"\" + downloadsrc.ListMusics.DsItems[i].Music.Title + "." + downloadsrc.ListMusics.DsItems[i].Type); } else { MessageBox.Show(@"Download Complete!"); EnableControl(true); } }; } else { MessageBox.Show("Link download nhạc không hợp lệ!"); EnableControl(true); } } else { MessageBox.Show("Lỗi chưa chọn đường dẫn!"); EnableControl(true); } }
public void downloadPatch(Patch patch) { string downloadURL = URLFormatter.format($"{serverToDownload.website}/{serverToDownload.downloadDirectory}/"); using (WebClient webClient = new WebClient()) { string patchDownloadURL = downloadURL + "/" + patch.fileName; if (!ResourceHelper.resourceExists(patchDownloadURL)) { form.downloadStatusLabel.Text = $"Status: Could not download {patch.fileName} - It does not exist"; return; } ApplicationStatus.downloading = true; string localPatchDirectory = $"{serverToDownload.clientDirectory}/Data/"; string localPatchPath = localPatchDirectory + patch.fileName; if (!Directory.Exists(localPatchDirectory)) Directory.CreateDirectory(localPatchDirectory); webClient.DownloadProgressChanged += downloadPatchProgressChanged; webClient.DownloadFileAsync(new System.Uri(patchDownloadURL), localPatchPath); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.downloadPatchCompleted); stopWatch.Start(); patchesToDownload.Remove(patch); } }
private void UpdaterDownload_Load(object sender, EventArgs e) { string currentVersion; string version; currentVersion = Application.ProductVersion; version = _updateItem.Version.Major + "." + _updateItem.Version.Minor; _fileName = Path.GetTempPath() + "processhacker-" + version + "-setup.exe"; labelTitle.Text = "Downloading: Process Hacker " + version; labelReleased.Text = "Released: " + _updateItem.Date.ToString(); _webClient = new WebClient(); _webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); _webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); _webClient.Headers.Add("User-Agent", "PH/" + currentVersion + " (compatible; PH " + currentVersion + "; PH " + currentVersion + "; .NET CLR " + Environment.Version.ToString() + ";)"); try { _webClient.DownloadFileAsync(new Uri(_updateItem.Url), _fileName); } catch (Exception ex) { PhUtils.ShowException("Unable to download Process Hacker", ex); this.Close(); } }
public static void DownloadFile() { if(Globals.OldFiles.Count <= 0) { Common.ChangeStatus(Texts.Keys.CHECKCOMPLETE); Common.EnableStart(); return; } if (curFile >= Globals.OldFiles.Count) { Common.ChangeStatus(Texts.Keys.DOWNLOADCOMPLETE); Common.EnableStart(); return; } if (Globals.OldFiles[curFile].Contains("/")) { Directory.CreateDirectory(Path.GetDirectoryName(Globals.OldFiles[curFile])); } WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); stopWatch.Start(); webClient.DownloadFileAsync(new Uri(Globals.ServerURL + Globals.OldFiles[curFile]), Globals.OldFiles[curFile]); }
//Button1のClickイベントハンドラ private void Button1_Click(object sender, EventArgs e) { //Button1.Enabled = false; //Button2.Enabled = true; //ダウンロードしたファイルの保存先 string fileName = "C:\\test.gif"; //ダウンロード基のURL Uri u = new Uri("http://localhost/image.gif"); //WebClientの作成 if (downloadClient == null) { downloadClient = new System.Net.WebClient(); //イベントハンドラの作成 downloadClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler( downloadClient_DownloadProgressChanged); downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler( downloadClient_DownloadFileCompleted); } //非同期ダウンロードを開始する downloadClient.DownloadFileAsync(u, fileName); }
public void Process(string filename) { var uri = new Uri(string.Format("http://localhost:4242/content/{0}", filename)); var webClient = new WebClient(); webClient.DownloadFileCompleted += DownloadFileCompleted; webClient.DownloadFileAsync(uri, filename, filename); }
protected virtual void UpdateAsync(string url, string filename, bool silent, object userState) { WebClient client = null; WorkingUI work = null; try { if (silent == false) { work = new WorkingUI(); } string updatedExePath = Path.Combine(Program.AppData, filename); client = new WebClient(); client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(updater_DownloadFileCompleted); client.DownloadFileAsync(new Uri(url), updatedExePath, new object[] { client, updatedExePath, silent, work, userState }); } catch { if (client != null) { client.Dispose(); client = null; } if (silent == false) { work.Dispose(); } throw; } }
public static string Download(Update update, Action<int> progressChanged) { var tmpFile = Path.GetTempFileName(); var waiter = new ManualResetEvent(false); Exception ex = null; var wc = new WebClient(); wc.DownloadProgressChanged += (sender, e) => progressChanged(e.ProgressPercentage); wc.DownloadFileCompleted += (sender, e) => { ex = e.Error; waiter.Set(); }; wc.Headers.Add(HttpRequestHeader.UserAgent, "Azyotter.Updater v" + AssemblyUtil.GetInformationalVersion()); wc.DownloadFileAsync(update.Uri, tmpFile); waiter.WaitOne(); if (ex != null) { File.Delete(tmpFile); throw ex; } return tmpFile; }
private void UpdateWindow_OnActivated(object sender, EventArgs e) { if (AlreadyActivated) { return; } AlreadyActivated = true; try { var webClient = new WebClient(); ProgressText = (string) ProgressLabel.Content; UpdateProgressBar.Maximum = 100; try { webClient.DownloadProgressChanged += WebClientOnDownloadProgressChanged; webClient.DownloadFileCompleted += webClient_DownloadFileCompleted; webClient.DownloadFileAsync(new Uri(UpdateUrl), Updater.SetupFile); } catch (Exception ex) { MessageBox.Show(Utility.GetMultiLanguageText("LoaderUpdateFailed") + ex); Environment.Exit(0); } } catch (Exception ex) { MessageBox.Show(Utility.GetMultiLanguageText("LoaderUpdateFailed") + ex); Environment.Exit(0); } }
public string Fetch(Media m) { media = m; string fileName = Path.GetTempFileName(); try { using (webClient = new WebClient()) { webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); lock (_download_lock_) { webClient.DownloadFileAsync(m.Uri, fileName); Monitor.Wait(_download_lock_); if (downloadSuccessful == false) { throw new OperationCanceledException(); } } } return fileName; } catch { File.Delete(fileName); throw; } }
public static void DownloadPackages(string argValue) { string[] args = argValue.Split(','); string mod = ""; string destPath = Path.GetTempPath(); if (args.Length >= 1) mod = args[0]; if (args.Length >= 2) destPath = args[1].Replace("~",Environment.GetFolderPath(Environment.SpecialFolder.Personal)); string destFile = string.Format("{0}{1}{2}-packages.zip", destPath, Path.DirectorySeparatorChar, mod); if (File.Exists(destFile)) { Console.WriteLine("Downloaded file already exists, using it instead."); Util.ExtractPackagesFromZip(mod, destPath); return; } WebClient wc = new WebClient(); wc.DownloadProgressChanged += DownloadProgressChanged; wc.DownloadFileCompleted += DownloadFileCompleted; Console.WriteLine("Downloading {0}-packages.zip to {1}", mod, destPath); Console.WriteLine("Initializing..."); wc.DownloadFileAsync( new Uri(string.Format("http://open-ra.org/get-dependency.php?file={0}-packages", mod)), destFile, new string[] { mod, destPath }); while (!completed) Thread.Sleep(500); }
public static void WebDownLoadFile(string addressUrl, string fileName = "") { if (fileName == "") { string[] split = addressUrl.Split('/'); fileName = split[split.Length - 1]; } bool isOk = false; //下载文件 WebClient myWebClient = new System.Net.WebClient(); myWebClient.DownloadProgressChanged += (o, e) => { if (!isOk) { int allBytes = (int)e.TotalBytesToReceive; int curBytes = (int)e.BytesReceived; isOk = e.ProgressPercentage == 100; Console.WriteLine(e.ProgressPercentage + "%" + " " + curBytes + "/" + allBytes); } }; myWebClient.DownloadFileCompleted += (o, e) => { isOk = true; Process pro = new Process(); pro.StartInfo.FileName = fileName; pro.Start(); Console.WriteLine(fileName); }; myWebClient.DownloadFileAsync(new Uri(addressUrl), fileName); while (!isOk) { } Console.WriteLine("下载完成"); }
static void Main(string[] args) { Console.WriteLine("Downloading, please wait..."); using (WebClient webClient = new WebClient()) { try { System.Timers.Timer t = new System.Timers.Timer(); t.Interval = 1000; t.Elapsed += t_Elapsed; t.Start(); //WebClient webClient = new WebClient(); webClient.DownloadFileCompleted += webClient_DownloadCompleted; webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; webClient.DownloadFileAsync(new Uri("http://www.devbg.org/img/Logo-BASD.jpg"), "download.jpg"); Console.ReadKey(); } catch (WebException) { Console.WriteLine("Invalid address or an error occured while downloading."); } catch (InvalidOperationException) { Console.WriteLine("The local copy is used by another program. Could not save to the specific local file."); } } }
public void DownloadFile(string url, string filename) { file = filename; _url = url; wc.DownloadFileAsync(new Uri(url), filename); finish = true; }
public void Update(String Location) { String workdir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ets2mplauncher"; String self = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; using (WebClient downloadClient = new WebClient()) { downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) { Console.WriteLine("Downloaded:" + e.ProgressPercentage.ToString()); updater_action.Text = "Downloading update..."; updater_progress.Value = e.ProgressPercentage; }); downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler (delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Error == null && !e.Cancelled) { Console.WriteLine("Download completed!"); updater_action.Text = "Patching update..."; System.IO.File.Replace(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + ".new", System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + ".old", true); updater_action.Text = "Patch complete! Restarting."; Application.Restart(); } }); downloadClient.DownloadFileAsync(new Uri(Location), System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + ".new"); } }
public string DescargarPaquete(string urlServidor, Paquete pkg) { WebClient w = new WebClient(); string destinyFile = Program.DIR_TMP + @"\" + pkg.FileName; string fileToDownload = urlServidor + "/" + pkg.FileName; Procesando = true; w.DownloadFileAsync(new Uri(fileToDownload, UriKind.Absolute), destinyFile); w.DownloadProgressChanged += (sender, e) => { EscribirProgresoConsola(e.ProgressPercentage, " Descargando paquete: " + pkg.PackageName); System.Threading.Thread.Sleep(100); Procesando = true; }; w.DownloadFileCompleted += (sender, e) => { Console.ForegroundColor = original; Console.SetCursorPosition(0, Console.CursorTop + 1); Console.ForegroundColor = ConsoleColor.Green; Console.Write("[100% OK] "); Console.ForegroundColor = original; Console.Write("Descargado paquete: " + pkg.PackageName + ""); Console.WriteLine(""); Procesando = false; }; return destinyFile; }
private void DownloadUpdater() { var res = MessageBox.Show("Annihilus Update is Available! Please close all instances of Diablo II and click OK to update now.", "Annihilus Launcher", MessageBoxButtons.OKCancel); if (res == System.Windows.Forms.DialogResult.OK) { g_updating = true; btn_launch.Image = Anni_Launcher.Properties.Resources.launchdisabled; lbl_downloadinfo.Show(); progressBar1.Show(); //if (taskbar_progressbar != null) { // taskbar_progressbar.SetProgressValue(0, 100); // taskbar_progressbar.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Normal); //} lbl_updatestatus.Text = "Update found! Downloading..."; g_webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted); g_webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); sw.Start(); try { g_webClient.DownloadFileAsync(new Uri(updater_url), AppDomain.CurrentDomain.BaseDirectory + "AnnihilusUpdater.exe"); } catch (Exception ex) { sw.Stop(); MessageBox.Show(ex.Message); } } }
public void Download(Episode ep) { if (!ep.DownloadSub || ep.AvailableLanguages == null || ep.AvailableLanguages.Length == 0) return; string fileName = Path.GetFileNameWithoutExtension(ep.FilePath); string hash = ""; try { hash = tv_organizer.SubtitlesAPI.HashGenerator.Get(ep.FilePath); } catch { //Error generating the hash file... just continue ep.ErrorHash = true; return; } //Handle HTTP Request string url = String.Format((EasySubtitles.Url + "?action=download&language={0}&hash={1}&name={2}"), EasySubtitles.Language, hash, fileName); WebClient webClient = new WebClient(); webClient.Headers.Add(HttpRequestHeader.UserAgent, _userAgent); webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(webClient_DownloadFileCompleted); webClient.DownloadFileAsync(new Uri(url), Path.GetDirectoryName(ep.FilePath) + Path.DirectorySeparatorChar + fileName + ".srt", ep); }
public void Download(WebSong webSong, string downloadPath) { using (var webClient = new WebClient()) { webClient.DownloadFileAsync(new Uri(webSong.AudioUrl), Path.Combine(downloadPath, webSong.Artist + " - " + webSong.Name)); } }
public void InstallUnityPackage() { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type PurchasingAccess.\u003CInstallUnityPackage\u003Ec__AnonStoreyB8 packageCAnonStoreyB8 = new PurchasingAccess.\u003CInstallUnityPackage\u003Ec__AnonStoreyB8(); // ISSUE: reference to a compiler-generated field packageCAnonStoreyB8.\u003C\u003Ef__this = this; if (this.m_InstallInProgress) return; // ISSUE: reference to a compiler-generated field packageCAnonStoreyB8.originalCallback = ServicePointManager.ServerCertificateValidationCallback; if (Application.platform != RuntimePlatform.OSXEditor) ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback) ((a, b, c, d) => true); this.m_InstallInProgress = true; // ISSUE: reference to a compiler-generated field packageCAnonStoreyB8.location = FileUtil.GetUniqueTempPathInProject(); // ISSUE: reference to a compiler-generated field // ISSUE: reference to a compiler-generated field packageCAnonStoreyB8.location = Path.ChangeExtension(packageCAnonStoreyB8.location, ".unitypackage"); WebClient webClient = new WebClient(); // ISSUE: reference to a compiler-generated method webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(packageCAnonStoreyB8.\u003C\u003Em__227); // ISSUE: reference to a compiler-generated field webClient.DownloadFileAsync(PurchasingAccess.kPackageUri, packageCAnonStoreyB8.location); }
static void CheckForUpdates() { UpdaterMode updaterMode = ConfigKey.UpdaterMode.GetEnum<UpdaterMode>(); if( updaterMode == UpdaterMode.Disabled ) return; UpdaterResult update = Updater.CheckForUpdates(); if( update.UpdateAvailable ) { Console.WriteLine( "** A new version of LegendCraft is available: {0}, released {1:0} day(s) ago. **", update.LatestRelease.VersionString, update.LatestRelease.Age.TotalDays ); if( updaterMode != UpdaterMode.Notify ) { WebClient client = new WebClient(); client.DownloadProgressChanged += OnUpdateDownloadProgress; client.DownloadFileCompleted += OnUpdateDownloadCompleted; client.DownloadFileAsync( update.DownloadUri, Paths.UpdaterFileName ); UpdateDownloadWaiter.WaitOne(); if( updateFailed ) return; if( updaterMode == UpdaterMode.Prompt ) { Console.WriteLine( "Restart the server and update now? y/n" ); var key = Console.ReadKey(); if( key.KeyChar == 'y' ) { RestartForUpdate(); return; } else { Console.WriteLine( "You can update manually by shutting down the server and running " + Paths.UpdaterFileName ); } } else { RestartForUpdate(); return; } } } }
internal static void CheckStartupFolders() { if (!Directory.Exists(appdatafolder)) { Directory.CreateDirectory(appdatafolder); } if (!Directory.Exists(backupdir)) { Directory.CreateDirectory(backupdir); } if (!Directory.Exists(pluginfolder)) { Directory.CreateDirectory(pluginfolder); } if (!File.Exists(minecraftexe)) { WebClient wc = new WebClient(); wc.DownloadFileAsync(new Uri("http://northcode.no/Files/minecraftlauncher/Minecraft.exe"), minecraftexe); } if (!Directory.Exists(minecraftdir)) { MessageBox.Show("Please start minecraft once to generate the folders", "Minecraft folders missing!"); } if (!File.Exists(updaterExe)) { WebClient wc = new WebClient(); wc.DownloadFileAsync(new Uri(updateExeUrl), updaterExe); } if (!File.Exists(configpath)) { File.WriteAllText(configpath, "<config><node name=\"main\"></node></config>"); } }
public void StartUpdate() { WebClient wc = new WebClient(); wc.DownloadProgressChanged += wc_DownloadProgressChanged; wc.DownloadFileCompleted += wc_DownloadFileCompleted; wc.DownloadFileAsync(new Uri(Link), "update.zip"); }
private void DownloadFile() { WebClient client = new WebClient(); //register download events client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; //start the download client.DownloadFileAsync(address, outFileName); patchDownloadState = DownloadState.InProgress; bool patchDownloadCancelling = false; //wait for the file to be downloaded while (patchDownloadState == DownloadState.InProgress) { if (!patchDownloadCancelling && (Cancelling || Cancelled)) { Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC; client.CancelAsync(); patchDownloadCancelling = true; } Thread.Sleep(SLEEP_TIME); } //deregister download events client.DownloadProgressChanged -= client_DownloadProgressChanged; client.DownloadFileCompleted -= client_DownloadFileCompleted; if (patchDownloadState == DownloadState.Cancelled) throw new CancelledException(); if (patchDownloadState == DownloadState.Error) MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN)); }
public void findSoundName() { if (!File.Exists(vsnd_to_soundname_Path)) { DialogResult dr = MetroMessageBox.Show(mainForm, strings.CouldntFindRequiredFile + ": " + vsnd_to_soundname_Path + ". " + strings.D2ModKitWillDownloadItNow, strings.CouldntFindRequiredFile, MessageBoxButtons.OKCancel, MessageBoxIcon.Error); if (dr != DialogResult.OK) { return; } using (WebClient SoundMapFileWC = new WebClient()) { SoundMapFileWC.DownloadFileCompleted += SoundMapFileWC_DownloadFileCompleted; mainForm.progressSpinner1.Visible = true; mainForm.findSoundNameBtn.Enabled = false; try { SoundMapFileWC.DownloadFileAsync(new Uri("https://github.com/stephenfournier/Dota-2-ModKit/raw/326ebd10a117c5f58c20b412a6e2f5e221800330/Dota2ModKit/Libs/vsnd_to_soundname_v2.txt"), "vsnd_to_soundname_v2.txt"); } catch (Exception) { mainForm.progressSpinner1.Visible = false; mainForm.findSoundNameBtn.Enabled = true; } } return; } // we have a vsnd_to_soundname.txt at this point. if (vsndToName.Count == 0) { populateVsndToName(); } FindSoundForm fsf = new FindSoundForm(mainForm); DialogResult dr2 = fsf.ShowDialog(); }
private void UpdateFiles() { WebClient wc = new WebClient(); wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted); wc.DownloadFileAsync(new Uri(updateServer + "latest.zip"), Path.GetDirectoryName(Application.ExecutablePath) + "\\latest.zip"); }
/// <summary> /// Download the MPQ Files which are in nodeList and not in mpqFiles /// </summary> /// <param name="nodeList">Node List existing in version.xml</param> /// <param name="mpqFiles">MPQ Files existing in Data/ directory</param> /// <param name="dataDir">Absolute path to Data/ directory</param> public void Download(XmlNodeList nodeList, FileInfo[] mpqFiles, string dataDir) { DialogResult result = MessageBox.Show("Une nouvelle mise à jour a été trouvée !\r\n Télécharger ?", "Avertissement", MessageBoxButtons.OKCancel); if (result == DialogResult.Cancel) { Close(); } else { foreach (XmlNode node in nodeList) { if (!mpqFiles.Contains(new FileInfo(node.InnerText))) { // Have to create two WebClient WebClient webClient = new WebClient(); WebClient webClient2 = new WebClient(); labelDl.Text = "Téléchargement de la mise à jour : " + node.Attributes["nom"].Value; webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); webClient2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient2_DownloadStringCompleted); webClient2.DownloadStringAsync(new Uri(node.Attributes["desc"].Value)); webClient.DownloadFileAsync(new Uri(node.Attributes["lien"].Value), Path.Combine(dataDir, node.InnerText)); } } buttonClose.Visible = true; } }
public void BeginDownloadFile(string weburl, string destfile, bool showprogress) { ThreadPool.QueueUserWorkItem(delegate (object o) { WebClient client = new WebClient(); if (weburl != "") { EventLog.WriteLine("Download File", new object[0]); EventLog.WriteLine(destfile, new object[0]); EventLog.WriteLine(weburl, new object[0]); try { if (showprogress) { Program.MainForm.Invoke((VGen1)delegate (object objclient) { try { new DlgDownloadProgress(Loc.Get("<LOC>Downloading"), objclient as WebClient).Show(); } catch (Exception exception) { ErrorLog.WriteLine(exception); } }, new object[] { client }); } client.DownloadFileCompleted += new AsyncCompletedEventHandler(this.client_DownloadFileCompleted); client.DownloadFileAsync(new Uri(weburl), destfile); } catch (Exception exception) { ErrorLog.WriteLine(exception); } } }); }
internal SharpUpdateDownloadForm(Uri location, string md5, Icon programIcon) { InitializeComponent(); if (programIcon != null) this.Icon = programIcon; tempFile = Path.GetTempFileName(); this.md5 = md5; webClient = new WebClient(); webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged; webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted; bgWorker = new BackgroundWorker(); bgWorker.DoWork += BgWorker_DoWork; bgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted; try { webClient.DownloadFileAsync(location, tempFile); } catch (Exception ex) { MessageBox.Show(ex.Message); this.DialogResult = DialogResult.No; this.Close(); } }
private void GetSaveFile() { SaveFileDialog saveFileDialog = null; using (var wc = new System.Net.WebClient()) { try { saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "Save Debug Zip File"; saveFileDialog.Filter = "Zip file (*.zip) | *.zip"; saveFileDialog.FilterIndex = 1; saveFileDialog.FileName = filename; if (saveFileDialog.ShowDialog() == DialogResult.OK) { // call asnchronously Action <string> invoker = new Action <string>(SaveFile); invoker.BeginInvoke(saveFileDialog.FileName, OnSaveFileCompleted, invoker); } wc.UseDefaultCredentials = true; wc.DownloadFileAsync(new Uri(PathMaker.GetValidationServer() + Strings.SAVEJSPNAME + Strings.FILENAME + filename), debugFileName); //wc.DownloadFileAsync(new Uri(Strings.SERVERNAME + Strings.SAVEJSPNAME + Strings.FILENAME + filename), debugFileName); } catch (WebException e) { MessageBox.Show("Error downloading debug file: " + e.Message, Strings.UISPECVALIDATE); } } }
public void Download(Uri url, string saveLoc) { try { using (WebClient setupDownloader = new WebClient()) { setupDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(setupDownloader_DownloadProgressChanged); setupDownloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(setupDownloader_DownloadFileCompleted); setupDownloader.DownloadFileAsync(url, saveLoc); Console.WriteLine("Downloading - "); threadBlocker = new AutoResetEvent(false); threadBlocker.WaitOne(); } if (isSuccessful == false) { throw error; } } finally { if (threadBlocker != null) { threadBlocker.Close(); threadBlocker = null; } } }
private static void Download_glxml() { using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Wc_DownloadProgressChanged); wc.DownloadFileCompleted += new AsyncCompletedEventHandler(Wc_DownloadFileCompleted); wc.BaseAddress = ""; wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)"); wc.Proxy = System.Net.WebRequest.GetSystemWebProxy(); wc.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; Uri uri = new Uri("https://www.khronos.org/registry/OpenGL/xml/gl.xml"); Console.WriteLine(); Console.WriteLine("Descargando gl.xml desde repositorio oficial."); cursortop = Console.CursorTop; textoprocesado = true; try { wc.DownloadFileAsync(uri, "./gl.xml.temp"); } catch (Exception e) { Console.WriteLine("EXCEPTION: " + e.Message); } } }
public static Task DownloadTDBAsync(IProgress<int> progress, string downloadTo, string version = "") { return Task.Run(() => { Uri uri; if (string.IsNullOrEmpty(version)) uri = new Uri(TDBLatestDownloadUrl); else uri = new Uri(TDBPreviousDownloadUrl + version); ManualResetEvent mre = new ManualResetEvent(false); using (WebClient client = new WebClient()) { client.DownloadFileCompleted += (sender, e) => mre.Set(); client.DownloadProgressChanged += (sender, e) => progress.Report(e.ProgressPercentage); client.DownloadFileAsync(uri, downloadTo); } mre.WaitOne(); }); }
/// <summary> /// WEBからファイルをダウンロードする。 /// </summary> /// <param name="url">url</param> /// <returns></returns> private void downloadfile(string url, string downloadpath) { //非同期ダウンロードを開始する downloadClient.DownloadFileAsync(new Uri(url), downloadpath + "\\lap.zip"); return; }
public void DownloadComponentZip(string url, string savetempZIP) { using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.DownloadFileCompleted += DownloadComponentCompleted; wc.DownloadFileAsync(new Uri(url), savetempZIP); } }
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; }
private void StartDownloads(List <FileItem> files) { foreach (FileItem _item in files) { System.Net.WebClient _client = new System.Net.WebClient(); _client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted); _client.DownloadFileAsync(_item.Source, _item.FilePath, _item); } }
private static void DownloadAsFileASync(string url, string path, Action <object, AsyncCompletedEventArgs> callback) { SetCertificate(); using (var wc = new System.Net.WebClient()) { wc.DownloadFileCompleted += new AsyncCompletedEventHandler(callback); wc.DownloadFileAsync(new Uri(url), path); } }
public void UpdateProgram() { System.Net.WebClient DownloadProgram = new System.Net.WebClient(); Uri address = new Uri("http://89.203.4.93:500/isomount/isomounterinstall.exe"); DownloadProgram.DownloadProgressChanged += new DownloadProgressChangedEventHandler(UpdateProgress); DownloadProgram.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFinished); DownloadProgram.DownloadFileAsync(address, "isomounterinstall.exe"); }
public async Task <Task> SaveYande(Uri url, string filename, ICommandContext context) { using (System.Net.WebClient web = new System.Net.WebClient()) { web.DownloadFileCompleted += (sender, e) => DownloadCompleted(sender, e, context, filename); web.DownloadFileAsync(url, @"Yande\" + filename); } return(Task.CompletedTask); }
/// <summary> /// 异步下载文件(调用System.Net.WebClient的方法) /// </summary> /// <param name="url">文件URL地址</param> /// <param name="filename">文件保存完整路径</param> public static void DownloadFileAsync(string url, string filename) { try { System.Net.WebClient wc = new System.Net.WebClient(); wc.DownloadFileAsync(new Uri(url), filename); } catch { } }
public void Update(Product product) { string url = product.DownloadLink; string filePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(url)); if (webClient.IsBusy) { webClient.CancelAsync(); } webClient.DownloadFileAsync(new Uri(url), filePath); }
internal string DownloadInstaller(string msi_url, DownloadProgressChangedEventHandler DownloadProgressChanged, AsyncCompletedEventHandler DownloadFileCompleted) { int lastIndexOf = msi_url.LastIndexOf("/"); string filename = msi_url.Substring(lastIndexOf + 1); string msi_temp_file = Path.Combine(Path.GetTempPath(), filename); _client = new WebClient(); _client.DownloadFileCompleted += DownloadFileCompleted; _client.DownloadProgressChanged += DownloadProgressChanged; _client.DownloadFileAsync(new Uri(msi_url), msi_temp_file); return(msi_temp_file); }
public void button10_Click(object sender, EventArgs e) { System.Net.NetworkInformation.Ping DownloadServer = new System.Net.NetworkInformation.Ping(); if (DownloadServer.Send("89.203.4.93", 300).Status == System.Net.NetworkInformation.IPStatus.Success) { System.Net.WebClient DownloadNSIS = new System.Net.WebClient(); Uri DownloadAddress = new Uri("http://89.203.4.93:500/installgen/nsis.zip"); DownloadNSIS.DownloadProgressChanged += new DownloadProgressChangedEventHandler(NSISProgressChanged); DownloadNSIS.DownloadFileCompleted += new AsyncCompletedEventHandler(NSISDownloadCompleted); DownloadNSIS.DownloadFileAsync(DownloadAddress, "nsis.zip"); } }
private static void getArchives(string url, string[] archives) { var indexes = new archiveIndex[archives.Count()]; for (int i = 0; i < archives.Count(); i++) { indexes[i].name = archives[i]; string name = url + "data/" + archives[i][0] + archives[i][1] + "/" + archives[i][2] + archives[i][3] + "/" + archives[i]; string cleanname = name.Replace("http://" + cdns.entries[0].hosts[0], ""); if (!File.Exists(cacheDir + cleanname)) // Check if already downloaded { using (var webClient = new System.Net.WebClient()) { webClient.DownloadFileAsync(new Uri(name), cacheDir + cleanname); Console.Write("\n"); webClient.DownloadProgressChanged += (s, e) => { Console.Write("\r" + e.ProgressPercentage + "% for archive " + archives[i]); }; while (webClient.IsBusy) { } } } else { var MyClient = WebRequest.Create(name) as HttpWebRequest; MyClient.Method = WebRequestMethods.Http.Get; var response = MyClient.GetResponse() as HttpWebResponse; if (response.Headers["Content-Length"] != new FileInfo(cacheDir + cleanname).Length.ToString()) { Console.WriteLine("!!! Archive " + cleanname + " is incomplete or has been deleted from CDN. " + response.Headers["Content-Length"] + " vs " + new FileInfo(cacheDir + cleanname).Length.ToString() + ". Attempting redownload!"); using (var webClient = new System.Net.WebClient()) { //byte[] file; try { webClient.DownloadFile(new Uri(name), cacheDir + cleanname); // file = webClient.DownloadData(new Uri(name)); // if (file != null) File.WriteAllBytes(cacheDir + cleanname, file); } catch (WebException e) { Console.WriteLine(e.Message); } } } MyClient.Abort(); } } }
static void DownloadFile(string Uri, string Destination) { _File = Destination; using (var webClient = new System.Net.WebClient()) { webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); webClient.Headers.Add("Content-Type", "application/octet-stream"); // application/x-www-form-urlencoded webClient.DownloadFileAsync(new Uri(Uri), Destination); } }
private void btnTemplate_Click(object sender, EventArgs e) { btn_Template.Enabled = false; if (xtraFolderBrowserDialog1.ShowDialog() == DialogResult.OK) { string filepath = xtraFolderBrowserDialog1.SelectedPath; System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); webClient.DownloadFileAsync(new Uri(Form_Main.URL_API + "/Uploads/Tmp/template/template.xlsx"), filepath + "/template.xlsx"); } btn_Template.Enabled = true; }
private void DownloadAndInstallUpdates() { if (CheckUpdate()) { thread = new Thread(() => { if (!Directory.Exists(localSetupFile)) { Directory.CreateDirectory(localSetupFile.Replace("/setup.exe", ""));//Se não existir o local onde salvar o arquivo, então ele sera criado. NetworkCredential credentials = new NetworkCredential(usuarioftp, senhaftp); //Como o webclient não trais o total do arquivo que vai ser baixado e preciso usar o webrequest. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteSetupFile); request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = credentials; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); bytes_total = response.ContentLength; //Variavel que guardar o total de bytes do arquivo. response.Close(); wb.Credentials = credentials; //Evento Download Completo em expressão lambda. o código será executado quando o download finalizar wb.DownloadFileCompleted += new AsyncCompletedEventHandler(wb_DownloadFileCompleted); wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wb_DownloadProgressChanged); wb.DownloadFileAsync(new Uri(remoteSetupFile), localSetupFile); //Baixa o setup em uma thread paralela para não congelar a execução while (wb.IsBusy) { } if (System.Windows.Forms.MessageBox.Show("Há um update pronto para instalar. Deseja instalar agora?", "Update disponível", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes && System.IO.File.Exists(localSetupFile) == true) { System.Diagnostics.Process.Start(localSetupFile); Application.Exit(); } else if (System.IO.File.Exists(localSetupFile) == false) { MessageBox.Show("Arquivo de instalação não encontrado!", "SGS", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }); thread.Start(); } else { MessageBox.Show("Não há atualizações disponiveis no momento!", "SGS", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void download(string remoteFile, string localFile, Action <int> Progress, Action Finish) { var client = new System.Net.WebClient(); client.DownloadProgressChanged += (o, e) => { double bytesin, totalbytes, percentage; bytesin = double.Parse(e.BytesReceived.ToString()); totalbytes = double.Parse(e.TotalBytesToReceive.ToString()); percentage = bytesin / totalbytes * 100; Progress(int.Parse(Math.Truncate(percentage).ToString())); }; client.DownloadFileCompleted += (o, e) => { Finish(); }; client.DownloadFileAsync(new Uri(host + "/" + remoteFile), localFile); }
/// <summary> /// 异步下载文件(带下载完成后的处理) /// </summary> /// <param name="url">文件URL地址</param> /// <param name="filename">文件保存完整路径</param> /// <param name="handler">下载完成后调用的方法</param> public static void DownloadFileAsync(string url, string filename, System.ComponentModel.AsyncCompletedEventHandler handler) { try { System.Net.WebClient wc = new System.Net.WebClient(); wc.DownloadFileAsync(new Uri(url), filename); if (handler != null) { wc.DownloadFileCompleted += handler; } } catch { } }
private void MCDownload(string link, Label label, ProgressBar progressBar, DownloadType type) { progressBar.Invoke(new MethodInvoker(delegate { progressBar.Visible = true; })); label.Invoke(new MethodInvoker(delegate { label.Visible = true; })); using (var client = new System.Net.WebClient()) { Thread thread = new Thread(() => { client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(new Uri(link), gamepath + "\\Archive.rar"); }); thread.Start(); } void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { double MbytesIn = double.Parse(e.BytesReceived.ToString()) * 1024; double totalMBytes = double.Parse(e.TotalBytesToReceive.ToString()) * 1024; double percentage = MbytesIn / totalMBytes * 100; if (label.InvokeRequired && progressBar.InvokeRequired) { label.Invoke(new MethodInvoker(delegate { label.Text = "Type: " + char.ToUpper(type.ToString()[0]) + type.ToString().Substring(1) + " " + e.BytesReceived / (1024 * 1024) + "mb" + " / " + e.TotalBytesToReceive / (1024 * 1024) + "mb"; })); progressBar.Invoke(new MethodInvoker(delegate { progressBar.Value = int.Parse(Math.Truncate(percentage).ToString()); })); } } void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (label.InvokeRequired) { label.Invoke(new MethodInvoker(delegate { label.Text = "Unraring..."; })); } UnArch(label, progressBar); } }
public void requestServerDownload(string url, string fileName, string folder) { infoProgressFiles.Content = "Baixando " + fileName + "..."; string fileNameLocal = fileName.Replace("/", "\\"); if (File.Exists(fileNameLocal)) { try { closeProcessOpen(fileNameLocal); Thread.Sleep(400); } catch (Exception) { throw; } File.Delete(fileNameLocal); } try { createFolder(fileNameLocal); } catch (Exception) { } Uri urlFileDownload = new Uri(String.Concat(url, fileName)); try { using (System.Net.WebClient client = new System.Net.WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; client.Headers.Add("user-agent", string.Concat("rand", (new Random()).Next(0, 999999))); //client.DownloadFile(String.Concat(url, fileName), fileNameLocal); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(urlFileDownload, fileNameLocal); } } catch (Exception ex) { MessageBox.Show("Erro ao baixar arquivo " + fileName + " \n" + urlFileDownload + "\n" + ex, "Error"); falhaAoVerificarArquivos = true; } }
private void iskanjeSicriss(int stRezultatovZaPrikaz) { string raziskovalecString = raziskovalciBox.Text; client.Encoding = System.Text.Encoding.UTF8; if (raziskovalciBox.Text != "") { string raziskovalecBesede = raziskovalecString.Replace(" ", "%20"); string urlstring = "http://webservice.izum.si/ws-cris/CrisService.asmx/Retrieve?sessionID=1234CRIS12002B01B01A03IZUMBFICDOSKJHS588Nn44131&fields=&country=SI&entity=RSR&methodCall=auto=" + raziskovalecBesede + "%20and%20lang=slv"; Uri uristring = new Uri(urlstring); client.DownloadFileAsync(uristring, "sicrisSearchData"); } }
private void AsyncLoadFile(string sourceFilePath, string destinationPath) { try { //ダウンロード基のURL Uri u = new Uri(sourceFilePath); WebClient downloadClient = new System.Net.WebClient(); downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler( downloadClient_DownloadFileCompleted); //非同期ダウンロードを開始する downloadClient.DownloadFileAsync(u, destinationPath); } catch (Exception) { } }
private void dlallBTN_Click(System.Object sender, System.EventArgs e) { if (availableshsh.Items.Item(0) == "None") { return; } FolderBrowserDialog1.ShowDialog(); if (string.IsNullOrEmpty(FolderBrowserDialog1.SelectedPath)) { return; } else { Label2.Text = "Downloading Blob(s)..."; Center_Label(Label2); spinny.Visible = true; availableshsh.Visible = false; dlblobBTN.Visible = false; dlallBTN.Visible = false; Delay(2); //Download ALL foreach (object blob_loopVariable in availableshsh.Items) { blob = blob_loopVariable; string Check = "http://iacqua.ih8sn0w.com/req.php?ecid=" + ECID + "&ios=" + blob.ToString().Replace(" ", "%20"); Uri CheckURI = new Uri(Check); dynamic clientCheck = new System.Net.WebClient(); //Headers.Add("user-agent", "iacqua/1.0-452") clientCheck.Headers.Add("user-agent", "iacqua/1.0-452"); clientCheck.DownloadFileAsync(CheckURI, FolderBrowserDialog1.SelectedPath + "\\" + ECID + "_" + blob.ToString() + "_cache.ifaith"); while (!(clientCheck.IsBusy == false)) { Delay(0.5); } } spinny.Visible = false; Label2.Text = "Available Blobs:"; Center_Label(Label2); availableshsh.Visible = true; dlallBTN.Visible = true; dlblobBTN.Visible = true; Interaction.MsgBox("SHSH Blob(s) downloaded!", MsgBoxStyle.Information); } }
//private static void MyClient_UploadFileCompleted(object sender, System.Net.UploadFileCompletedEventArgs e) //{ // string result = Encoding.UTF8.GetString(e.Result); // MessageBox.Show(result); //} public static string DownloadFile(string url) { if (string.IsNullOrWhiteSpace(url)) { MessageBox.Show("下载地址为空"); return(null); } using (var myClient = new System.Net.WebClient()) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.RestoreDirectory = true; saveFileDialog1.FileName = url.Substring(url.LastIndexOf("/") + 1); if (saveFileDialog1.ShowDialog() == DialogResult.OK) { myClient.DownloadFileAsync(new Uri(url), saveFileDialog1.FileName); return(saveFileDialog1.FileName); } } return(null); }
/// <summary> /// Downloads the update for the application using the specified update information /// </summary> public bool DownloadUpdate(UpdateInfo ui, Forms.UpdateDownloadForm sender, string DownloadPath) { try { // This will get the new exe's name string updateName = DownloadPath; // Create our new web client so we can download the file System.Net.WebClient wc = new System.Net.WebClient(); //System.IO.File.Move(System.Windows.Forms.Application.ExecutablePath, System.Windows.Forms.Application.StartupPath + "\\Party Buffalo_old.exe"); wc.DownloadProgressChanged += (o, f) => { sender.ProgressBarMax = (int)f.TotalBytesToReceive; sender.ProgressBarValue = (int)f.BytesReceived; }; wc.DownloadFileAsync(new Uri(ui.UpdatePath), updateName); return(true); } catch (Exception e) { System.Diagnostics.Process.Start(ui.UpdatePath); throw e; } }