开发者

C# cannot save file from url with proxy

开发者 https://www.devze.com 2023-04-11 06:13 出处:网络
I\'m trying to download a file from a url. I try two approachs but it isn\'t working with external files.

I'm trying to download a file from a url. I try two approachs but it isn't working with external files.

I think it's happening because I have internet over proxy. I can download internal network files (images, mp3, mp4, whatever...) but when I try to download something in external network it gives me timeout or 404 Not Found.

1st approach: System.Net.WebResponse, System.IO.FileStream

     try
        {
            var credentials = new NetworkCredential("myNetworkUserName", "myNetworkPassword", "myNetworkDomain");
            var proxy = WebProxy.GetDefaultProxy(); //new WebProxy("myNetworkProxy") <-- I TRY BOOTH WAYS
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg"); //External image link

            proxy.Credentials = credentials;

            request.Proxy = proxy;

            responseExternalImage = request.GetResponse();//explode here ex=""Unable to connect to the remote server""

            string fileName = GetFileName(response.ResponseUri.OriginalString);
                Stream stream = response.GetResponseStream();

                using (BinaryReader br = new BinaryReader(stream))
                {
                    content = br.ReadBytes(50000000);//perto de 50Mb
                    br.Close();
                }
                response.Close();

                FileStream fs = new FileStream(pathToSaveFile + "\\" + fileName, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                try
                {
                    bw.Write(content);
                }
                finally
                {
                    fs.Close();
                    bw.Close();
                }
        }
        catch (Exception ex)
        {

        }

The exception caught at GetResponse() says: "Unable to connect to the remote server", ""A connection attempt failed because the connected party did not proper开发者_StackOverflowly respond after a period of time, or established connection failed because connected host has failed to respond 77.238.160.184:80""


2nd approach: System.Net.WebClient, DownloadFile

      try
        {
            var credentials = new NetworkCredential("xpta264", ConfigurationManager.AppSettings["Xpta264Password"], "ptsi");
            var proxy = WebProxy.GetDefaultProxy();
            proxy.Credentials = credentials;

            // Create a new WebClient instance.
            using (WebClient myWebClient = new WebClient())
            {
                myWebClient.Proxy = proxy;
                // Download the Web resource and save it into the current filesystem folder.
                myWebClient.DownloadFile("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg", pathToSaveFile + "\\testImage.jpg");
            }
        }
        catch (Exception e)
        {

        }

The exception was caught at DownloadFile method and gives me the same error.

Hope someone can help me.

Sorry for my English


WebProxy.GetDefaultProxy() is obsolete and doesn't handle all cases. From the docs:

Note: This API is now obsolete.

The GetDefaultProxy method does not pick up any dynamic settings that are generated from scripts run by Internet Explorer, from automatic configuration entries, or from DHCP or DNS lookups.

Applications should use the WebRequest.DefaultWebProxy property and the WebRequest.GetSystemWebProxy method instead of the GetDefaultProxy method.

A better approach is to try to request a url and see if a proxy was used. I use this code in my own production system and it seems to work pretty well. Once you find the proxy, you can cache the address somewhere:

WebProxy proxy = null;

Uri testUri = new Uri("http://www.example.com/"); // replace with REAL url
Uri proxyEndpoint = WebRequest.GetSystemWebProxy().GetProxy(testUri);
if (!testUri.Equals(proxyEndpoint))
    proxy = new WebProxy(proxyEndPoint.ToString());

You can also just try calling WebRequest.GetSystemWebProxy() and see if that gives you the proxy, but I remember having problems with that which is why I went the request route above. YMMV.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号