webclient.downloadfile

G

Guest

Hi,
I am trying to download a file from a remote webserver. I create the
following:

string username="remoteusername";
string password="remotepassword";
string URI="http://remote.target.server/getdocument.asp?ID=sometest.pdf";

NetworkCredential nc = new NetworkCredential(username, password);
WebRequest req = WebRequest.Create(URI);
req.Credentials = nc;
WebResponse resp = req.GetResponse();
using(FileStream fsb = new FileStream(filename, FileMode.CreateNew))
{
BinaryWriter bw = new BinaryWriter(fsb);
Byte[] read = new Byte[1024];
int bytes = resp.GetResponseStream().Read(read, 0, 1024);
...
// Carry on and stream the bytes to a local file




If I set the URI to a file in a directory on my localhost webserver (and
change the username and password) this works a treat. When I try to download
the remote file, I get 403 - Access forbidden. Unfortunately if a just enter
the URI into IE, I can view the file on screen. So I know I have permission,
I know the file exists, and I know the code works coz it works for the local
file.
Can anyone tell me where I'm going wrong?

Thanks,

Martin
 
R

Rasmoo

I'd recommend 2 things:

1) Read the whole message returned by the webserver, i.e. catch the
WebException that is thrown during the call to GetResponse, and use
the Response property of the WebException to get the whole answer.
The web server may actually be kind enough to provide information.
Here's a quickly hacked example:

try
{
WebResponse resp = req.GetResponse();
}
catch (WebException e)
{
Stream respStream = e.Response.GetResponseStream();
byte[] buffer = new byte[8192];
int amt = respStream.Read(buffer, 0, buffer.Length);
Console.Write(Encoding.ASCII.GetString(buffer, 0, amt));
return;
}

2) Use the information obtained from 1). It might be as simple as

req.CookieContainer = new CookieContainer();

Happy hunting,
Ras
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top