Monday, March 5, 2012

Download File using Webrequest w/ Credentials

Code:
  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(); }  
            } 

0 comments:

Post a Comment