【问题标题】:Automate WebBrowser.ShowSaveAsDialog() or alternative method自动化 WebBrowser.ShowSaveAsDialog() 或替代方法
【发布时间】:2012-04-12 18:52:56
【问题描述】:

基本上我不想保存加载到 webBrowser 控件中的图像。目前我可以让它工作的唯一方法是显示另存为对话框。

有没有办法通过路径并使其自我保存? (隐藏我要求显示的对话框!)

还有其他保存图片的方法吗?我似乎无法让文档流工作。我也尝试过webclient.filedownload(...),但收到错误 302 ("(302) Found Redirect.")

DownloadFileAsync 没有给出错误但一个空的 jpeg 文件?

文件总是 jpeg,但并不总是在同一个位置。

【问题讨论】:

    标签: c# webbrowser-control download webclient imagedownload


    【解决方案1】:

    你应该选择HttpWebRequest。

    它具有自动跟随 302 的能力。

    var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com"); 
    //increase this number if there are more then one redirects. 
    myHttpWebRequest.MaximumAutomaticRedirections = 1;
    myHttpWebRequest.AllowAutoRedirect = true;
    var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();    
    
    var buff = new byte[myHttpWebResponse.ContentLength];
    
    // here you specify the path to the file. The path in this example is : image.jpg
    // if you want to store it in the application root use:
    // AppDomain.CurrentDomain.BaseDirectory + "\\image.jpg"
    using (var sw = new BinaryWriter(File.Open("c:\\image.jpg", FileMode.OpenOrCreate)))
    {
        using (var br = new BinaryReader (myHttpWebResponse.GetResponseStream ()))
        {
            br.Read(buff, 0, (int)myHttpWebResponse.ContentLength);
            sw.Write(buff);
        }            
    }
    

    【讨论】:

    • 是的,我在其他地方读过应该可以工作,我尝试了你的代码,仍然得到 302?文件保存在哪里?(如何指定输出路径)
    • 其中有一个小错误。 :) 试试这个。可以分享重定向图片的链接吗?
    • 我被告知我无法共享数据。第 4 行仍然出现重定向错误。我可以阻止重定向吗?我不明白为什么会发生这种情况,当您在网络浏览器中查看个人资料图片时,它显示正常并停留在图片上,无处重定向?
    • 如果我设置:myHttpWebRequest.AllowAutoRedirect = false;它转到下一行,但是对于字节来说太大了?
    • 不,它收到错误@line4 并停止,如果您将自动重定向更改为 false,我将进入下一行,希望这是向前迈出的一步。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多