Download File Using Webrequest With Credentials In C#
Here's a C# code that will download a file from source with credentials (password and username). This assumes that the source directory is password protected.
HttpWebRequest request;
HttpWebResponse response = null;
try
{
string username = "xxxuser";
string password = "yyypass";
NetworkCredential myCredentials =
new NetworkCredential(username, password);
request = (HttpWebRequest)WebRequest.Create(ListURL);
request.Timeout = 900000000;
request.Credentials = myCredentials;
request.AllowWriteStreamBuffering = false;
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//Write to disk
FileStream fs = new FileStream("\\192.168.3.3\xmldata.xml"
, FileMode.Create);
byte[] read = new byte[256];
int count = s.Read(read, 0, read.Length);
while (count > 0)
{
fs.Write(read, 0, count);
count = s.Read(read, 0, read.Length);
}
//Close everything
fs.Close();
s.Close();
response.Close();
}
catch (WebException e)
{
if (response != null){ response.Close(); }
}
Comments
Post a Comment