c# - 如何在不使用“文件下载”对话框的情况下使用 WebBrowser 控件下载文件?
解决方案
您不需要为此使用浏览器控件。
这是一个完整的工作示例。(根据需要更改路径。)
private void Button_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.DownloadFileAsync(new Uri("https://www.example.com/filepath"), @"C:\Users\currentuser\Desktop\Test.png");
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadProgressChanged += Client_DownloadProgressChanged;
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
TBStatus.Text = e.ProgressPercentage + "% " + e.BytesReceived + " of " + e.TotalBytesToReceive + " received.";
}
private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
MessageBox.Show("Download Completed");
}
您可以使用默认应用打开下载的文件,如下所示:
System.Diagnostics.Process.Start(@"C:\Users\currentuser\Desktop\Test.png");
编辑:
如果您的目标只是显示 png,则可以将其下载到流中,然后将其显示在图像控件中。
完整的工作样本。
WebClient wc = new WebClient();
MemoryStream stream = new MemoryStream(wc.DownloadData("https://www.dropbox.com/s/l3maq8j3yzciedw/App%20in%205%20minutes.PNG?raw=1"));
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream);
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = stream;
bi.EndInit();
image1.Source = bi;
这是异步版本。
private void Button_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadDataAsync(new Uri("https://www.dropbox.com/s/l3maq8j3yzciedw/App%20in%205%20minutes.PNG?raw=1"));
wc.DownloadDataCompleted += Wc_DownloadDataCompleted;
}
private void Wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
MemoryStream stream = new MemoryStream((byte[])e.Result);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream);
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = stream;
bi.EndInit();
image1.Source = bi;
}
推荐阅读
- c++ - 如何做类似的事情:“你的号码是”+号码“。” 在 C++ 中?
- arm - ARM-V7-A ADD指令结合LSL
- json - 检查数组是否为空或不颠簸转换
- python - 如何使用 pandas 和 PyMySQL 将 Excel 数据发送到 MySQL?
- python - 如何连接两个不同的数据框并将列中的值替换为另一列中的值?
- python - 带有“import bokeh”的烧瓶,带有 2 个没有外部散景服务器的散景图,而不是“模型只能由一个文档拥有”
- r - 部署在 shinyapp.io 中的闪亮应用程序中的理想时间问题
- javascript - 添加 - 在 ReactJS 中的字符串中
- android - 颤振警报应用程序,仅通过 java 和 Objective-C 代码安排警报?
- node.js - 如何在一个redis上保存2个数据?