如何更改权限级别,下载文件

时间:2013-10-09 19:52:53

标签: c# winforms url browser download

我尝试创建一个Web浏览器。目前,我尝试实现一种功能,如果用户想要下载某个文件,则会显示一个附加窗口,其中包含已下载文件的列表。如果文件已经加载,则会显示一条消息(只是一个想法)。

到目前为止,我在主窗体中获得了一个指向文件位置的链接,并将其发送到另一个窗体:

DownLoadFile dlf = new DownLoadFile();
...
        WebBrowser wb = new WebBrowser();
        wb.Navigating += new WebBrowserNavigatingEventHandler(wb_Navigating);
...
    private void wb_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
...
        if (e.Url.ToString().EndsWith(".mp3"))
        {
            dlf.DownloadPath = e.Url;
            dlf.Show();
        }
    }

在新表单中,我尝试使用此链接进行文件下载:

public Uri DownloadPath { get; set; }
...

private void DownLoadFile_Load(object sender, EventArgs e)
    {
        string filePath = null;

        //get FileName from URL 
        string[] ArrayForName;
        ArrayForName = DownloadPath.ToString().Split('/');
        saveFileDialogFile.FileName = 
            ArrayForName[ArrayForName.Length-1].Replace("%"," ").Trim();

        if (saveFileDialogFile.ShowDialog() == DialogResult.OK)
        {
            WebClient client = new WebClient();
            //get Url
            Uri url = new Uri(DownloadPath.ToString());     
            //get place where want to save with default name
            filePath = saveFileDialogFile.FileName;
            //event for result
            client.DownloadFileCompleted += 
                new System.ComponentModel.AsyncCompletedEventHandler (client_DownloadFileCompleted);
            //download
            client.DownloadFileAsync(url, filePath);
        }
    }

    void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        MessageBox.Show("Compleated");
    }

我的问题是:

  1. 关于if (e.Url.ToString().EndsWith(".mp3")) - 我怎么样? 改变这一点,不仅知道用户试图下载mp3文件, 但所有类型的文件 - 也许有更好的方式

  2. 如果我想直接使用某个链接下载文件,我会收到消息“目前您还没有获得相应的权限” - 我该怎么办? 更改我的网络浏览器的权限级别

  3. 如果我最终获得了该文件的链接并开始下载,结果只是文件名(文件大小为0 kb) - 我错了。

1 个答案:

答案 0 :(得分:0)

我的解决方案(也许不是最好的解决方案)

为webBrowser创建事件

wb.Navigating += new WebBrowserNavigatingEventHandler(wb_Navigating);

并在此活动中使用下一个

        if (GetWorkingWebBrowser().StatusText != null)
        {
            try
            {
                WebRequest request = WebRequest.Create(GetWorkingWebBrowser().StatusText);
                request.Method = "HEAD";

                using (WebResponse response = request.GetResponse())
                {
                    if (response.ContentLength > 0 && 
                         !response.ContentType.ToString().ToLower().Contains("text/html"))
                    {
                        dlf.DownloadPath = e.Url; //move url to my form for dwnload
                        dlf.Show(); //show form
                    }
                }
            }
            catch (UriFormatException)
            {
            }
            catch (WebException)
            {
            }
        }

GetWorkingWebBrowser() - 在标签上返回当前有效webBrowser的方法,meas webBrowser

相关问题