title: How to use HttpWebRequest to download file
body: <p>Trying to download file in code.  </p>
  
  <p>Current code:</p>
  
  <pre><code>  Dim uri As New UriBuilder
      uri.UserName = "xxx"
      uri.Password = "xxx"
      uri.Host = "xxx"
      uri.Path = "xxx.aspx?q=65"
  
     Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri.Uri), HttpWebRequest)
  
      request.AllowAutoRedirect = True
  
      request = DirectCast(WebRequest.Create(DownloadUrlIn), HttpWebRequest)
      request.Timeout = 10000
      'request.AllowWriteStreamBuffering = True
  
      Dim response As HttpWebResponse = Nothing
      response = DirectCast(request.GetResponse(), HttpWebResponse)
      Dim s As Stream = response.GetResponseStream()
  
      'Write to disk
      Dim fs As New FileStream("c:\xxx.pdf", FileMode.Create)
  
      Dim read As Byte() = New Byte(255) {}
      Dim count As Integer = s.Read(read, 0, read.Length)
      While count &gt; 0
          fs.Write(read, 0, count)
          count = s.Read(read, 0, read.Length)
      End While
  
      'Close everything
      fs.Close()
      s.Close()
      response.Close()
  </code></pre>
  
  <p>Running this code and checking the response.ResponseUri indicates im being redirected back to the login page and not to the pdf file.  </p>
  
  <p>For some reason its not authorising access what could I be missing as Im sending the user name and password in the uri? Thanks for your help</p>