我尝试使用System.Windows.Forms.WebBrowser
或System.Windows.Controls.WebBrowser
限制文件一次下载文件。
我尝试在System.Windows.Forms.WebBrowser.FileDowload
事件中捕获此信息,但无法知道文件何时完全下载。
有没有什么办法可以在Windows.Forms.WebBrowser
或Windows.Controls.WebBrowser
完成文件下载的时间。
感谢。
void descargaCompleta(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// When the download is complete
descargando = false;
}
void solo1Descarga (object sender, System.EventArgs e)
{
System.Windows.Forms.WebBrowser web = (System.Windows.Forms.WebBrowser)sender;
// Ask for Mutex
descargas.WaitOne();
descargando = true;
while (descargando)
;
descargas.ReleaseMutex();
}
// Función que Modifica la GUI
private void UpadteTabs()
{
WindowsFormsHost contWeb = new WindowsFormsHost();
System.Windows.Forms.WebBrowser nav = new System.Windows.Forms.WebBrowser();
// I set the Events to WebBrowser
nav.FileDownload += new EventHandler (solo1Descarga);
nav.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler (descargaCompleta);
}
注意:"一次下载文件"表示下载单个可以同时进行。 例如,如果您尝试下载大型文件和图像,则其中一个文件需要等待另一个文件
答案 0 :(得分:0)
您可以使用WebReponse
下载文件
WebRequest request = WebRequest.Create(fileUri);
WebResponse response = request.GetResponse();
DownLoadFile(response, response.ContentLength);
private void DownLoadFile(HttpWebResponse response, long contentLength)
{
var respContentType = response.ContentType.ToUpper();
using (var fileStream = File.OpenWrite(fileName))
{
using (var responseStream = response.GetResponseStream())
{
var buffer = new byte[1024];
int bytesRead;
int offset = 0;
//Thread.Sleep(100);
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0)
{
fileStream.Write(buffer, 0, bytesRead);
offset += bytesRead;
}
if (offset != response.ContentLength)
{
//return string.Format("Only downloaded {0} of {1} bytes", offset, response.ContentLength));
throw new ApplicationException(string.Format("Only downloaded {0} of {1} bytes",
offset, response.ContentLength));
}
}
}
}
Alternativly写一个while循环来读取二进制数据
public void DownloadFile(Uri uri, string filePathToSave)
{
var downloadedData = webClient.DownloadData(uri);
while (downloadedData.Length == 0)
{
Thread.Sleep(2000);
downloadedData = webClient.DownloadData(uri);
}
Stream file = File.Open(filePathToSave, FileMode.Create);
file.Write(downloadedData, 0, downloadedData.Length);
file.Close();
}