rejetto forum

[Solved] How to download file using WebClient in C#?

0 Members and 1 Guest are viewing this topic.

Offline 466046020

  • Occasional poster
  • *
    • Posts: 4
    • View Profile
Hi, All

For Specific purpose, I write a WinForm program to display the HFS page through WebBrowser. When a user click a file, I intercept it, and get the URL of this file. I want to use WebClient to download it, and display it in my own Form. But there is an ERROR:

Intercept the file click:
private void web_browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    String url_str = e.Url.ToString();

    if (url_str.Substring(url_str.Length - 3).ToLower() == "pdf")
    {
        label1.Text = e.Url.ToString();
        e.Cancel = true;
        file_url = e.Url;
        //DownloadFile(e.Url.ToString());
    }
}


Then I use WebClient to download it:
private void DownloadFile()
{
    String local_file = System.IO.Path.GetTempPath() + "temp.pdf";


    String temp_url;// = System.Web.HttpUtility.UrlEncode(file_url.ToString());
    temp_url = @"http://eric.xin:%78%69%6E%36%31%35%36%34%36%36@192.168.1.209:9050/02%E6%8A%80%E6%9C%AF%E7%9F%A5%E8%AF%86%E5%BA%93/06%E9%A1%B9%E7%9B%AE%E7%AE%A1%E7%90%86%EF%BC%88%E6%B5%B7%E6%9E%97%EF%BC%89/How%20to%20fix%20LOST%20CARD.pdf";
    WebClient client = new WebClient();
    client.DownloadFile(temp_url, local_file);

}


The URL contains user and password. I get an ERROR:
The remote server returned an error: (401) Unauthorized.

How to fix it?
« Last Edit: March 21, 2017, 12:39:53 PM by Mars »


Offline Mars

  • Operator
  • Tireless poster
  • *****
    • Posts: 2059
    • View Profile
Your temporary url uses access rights and has characters interpreted as unicode, hfs is not able to transcribe them into a correct path to deliver the file, complicating situations is not the Best choice to avoid error messages




Offline 466046020

  • Occasional poster
  • *
    • Posts: 4
    • View Profile
Problem Solved!

Use Credentials of WebClient, not just pass user and pass through URL:

String temp_url = @"http://host:port/filename.pdf";
String local_path = @"D:\test.pdf";
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("user","pass");
client.DownloadFile(temp_url, local_path);


Tnanks, everyone!
« Last Edit: March 21, 2017, 02:19:15 AM by 466046020 »