自动选择对话框中的保存c#

时间:2014-02-20 01:31:53

标签: c# regex dialog

我正在C#中构建一个应用程序,它使用Web浏览器打开指向.jpg的链接(下载它)。

某些浏览器会自动下载,而其他浏览器会打开一个对话框。在默认webBrowser1上,它显示一个对话框 open save cancel 。我的应用程序有没有办法自动选择 save


继续阅读有关该项目的更多信息:

我在表单中有3个Web浏览器。

webBrowser1 在表单加载时打开一个页面,并有一个按钮:

  • 使用正则表达式在页面上搜索特定链接。然后保存它们 到公共静态数组=> links[]

  • 打开webBrowser2

  • 隐藏按钮

  • 隐藏webBrowser1

webBrowser2

  1. 在加载时打开第一个链接=> links[0]

  2. 在webBrowser2上加载检查它是否包含regex2

  3. 如果为true,请使用regex3 =>查找其他链接(.jpg链接) second_links[](只能没有或1)

    • 如果没有链接返回到第1步
  4. webBrowser3 中打开链接second_links[0]。 (这个位可能会导致错误,因为它会在webBrowser3保存.jpg之前返回到第1步。有关如何绕过它的任何想法吗?)

3 个答案:

答案 0 :(得分: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();
        }
    }
}

答案 1 :(得分:0)

根据评论中的建议,直接下载文件。

例如:

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);
}

答案 2 :(得分:0)

为简单起见,您可以使用以下内容:

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.
}
相关问题