[英]Automatically select save in dialog box c#
我正在C#中构建一个应用程序,该应用程序使用Web浏览器(下载)打开到.jpg
的链接。
某些浏览器将自动下载,而另一些浏览器将打开一个对话框。 在默认的webBrowser1
它显示一个打开 保存 取消对话框。 我的应用程序可以自动选择保存吗?
我在表单中有3个Web浏览器。
webBrowser1在表单加载时打开一个页面,并具有一个按钮,该按钮:
使用正则表达式搜索页面上的特定链接。 然后将它们保存到公共静态数组=> links[]
。
打开webBrowser2
隐藏按钮
隐藏webBrowser1
webBrowser2
加载时打开第一个链接=> links[0]
在webBrowser2上加载检查是否包含regex2
如果为true,则使用regex3 => second_links[]
(只能是一个或一个)找到另一个链接( .jpg
链接)。
在webBrowser3中打开链接second_links[0]
。 (此位可能会导致错误,因为它会在webBrowser3保存.jpg
之前返回步骤1。有关如何解决该问题的任何想法?)
这是一个如何使用HttpClient下载jpeg文件的示例。 请注意,这假设使用VS2012并使用async / await。 您需要在项目中引用System.Net.Http才能进行此构建。
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
namespace DownloadSample
{
class Program
{
static async void RunClient(string address)
{
HttpClient client = new HttpClient();
// Send asynchronous request
HttpResponseMessage response = await client.GetAsync(address);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously and save asynchronously to file
using (FileStream fileStream = new FileStream("c:\\temp\\logo.jpg", FileMode.Create, FileAccess.Write, FileShare.None))
{
await response.Content.CopyToAsync(fileStream);
}
}
static void Main(string[] args)
{
string microsoft_logo = "http://c.s-microsoft.com/en-au/CMSImages/mslogo.png?version=856673f8-e6be-0476-6669-d5bf2300391d";
RunClient(microsoft_logo); //"http://some.domain.com/resource/file.jpg");
Console.WriteLine("Check download folder");
Console.ReadLine();
}
}
}
根据注释中的建议,直接下载文件。
例如:
var client = new HttpClient();
var clientResponse = await client.GetByteArrayAsync(imageUri);
clientResponse
是将包含图像的byte[]
。
写入磁盘:
using (var fs = new FileStream("path_to_file", FileMode.Create))
{
fs.Write(clientResponse, 0, clientResponse.Length);
}
为了简单起见,您可以使用以下内容:
var filename = @"C:\image.png";
var url = @"http://www.somedomain.com/image.png";
using (var client = new System.Net.WebClient())
{
client.DownloadFile(url, filename);
}
using (var image = System.Drawing.Image.FromFile(filename))
{
// Do something with image.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.