如何自动下载文件? [英] How to download file automatically?

查看:84
本文介绍了如何自动下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有一个网站给我一个文件。当我在浏览器中打开URL时,我得到一个文件。



我使用下面的代码

Hello,
I have one site which give me one file. When i open URL in Browser that time i get one file.

I have use below code

webBrowser1.Navigate(uri);





但这将打开保存对话框。我不使用保存对话框。我想在导航webBrowser时直接下载文件。



请帮帮我



我是什么尝试过:



我尝试下载webBrowser1.Navigate(uri)方法,但会打开另存为对话框。



But this will open save dialog. I do not use save dialog box. I want to directly download file when navigate webBrowser.

Please Help me

What I have tried:

I try webBrowser1.Navigate(uri) method for download but it will open Save As Dialog.

推荐答案

Method:-1 Download File Synchronously
The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).




using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");





方法:-2异步下载文件



Method:-2 Download File Asynchronously

To download file without blocking the main thread use asynchronous method DownloadFileA­sync. You can also set event handlers to show progress and to detect that the file is downloaded.







private void btnDownload_Click(object sender, EventArgs e)
{
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}


由于多种原因,您无法执行此操作。主要的和显而易见的是安全性...你想要一个网站在硬盘上保存文件吗?
You can't do this for a number of reasons. The main and obvious one being security...would you want a website saving files on your hard drive?


这篇关于如何自动下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆