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 properly 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