Downloading file from web page with authentification?

I want to download a file from website with authentification system.
Ok, maybe ill do some explanation. First of all, i open the site using webbrowser control. Then i logon, using following code:

WebBrowser1.Document.DomDocument.All("uid").Value = "User"
WebBrowser1.Document.DomDocument.All("pwd").Value = "Password"
ButtonClick(("login"), WebBrowser1) //ButtonClick is predefined function

Everything is ok, webbrowser loads the page and i see that i am logged in. Then i open another URL in same site. Still loged in. Get its source in textbox with:

Src.Text = WebBrowser1.DocumentText.ToString

Then with some InStr's i get URL to file which looks like http://site/download.php?id=ee290450a74a864425f54df5430298177b061202&f=[some filename]. id is allways a different string. Then i try to download it with many functions from web like:

Public Sub DownFile(ByVal sFile As String, ByVal sRemoteUrl As String)
Dim wr As HttpWebRequest
Dim ws As HttpWebResponse
Dim str As Stream
Dim inBuf(1000000) As Byte
Dim bytesToRead As Integer = CInt(inBuf.Length)
Dim bytesRead As Integer = 0
wr = CType(WebRequest.Create(sRemoteUrl), HttpWebRequest)
ws = CType(wr.GetResponse(), HttpWebResponse)
str = ws.GetResponseStream()
While bytesToRead > 0
Dim n As Integer = str.Read(inBuf, bytesRead, bytesToRead)
If n = 0 Then
Exit While
End If
bytesRead += n
bytesToRead -= n
End While
Dim fstr As New FileStream(sFile, FileMode.OpenOrCreate, FileAccess.Write)
fstr.Write(inBuf, 0, bytesRead)
End Sub


Public Sub GetPackage(ByVal sFile As String, ByVal destination As String, ByVal sRemoteUrl As String)
Dim wc As New Net.WebClient()
wc.DownloadFile(sRemoteUrl + sFile, destination + "\" + sFile)
MsgBox("Unable to download file " + sRemoteUrl + sFile)
End Try
End Sub

I get a file, but it actually is HTML page that says that i cant download, because i am not logged in (same as i would get if i try to open that link in any browser when not logged in). Looks like it has something to do with cookies, but i'm not sure about that. Strange, but in vb6 any function successfully downloads a file, i never saw such a problem there.


  • So what is happening here is the site you are using probably has some kind of cookie or something that it is using to identify your login session. When you switch to using something other than the webbrowser that you created the session with - you lose it.

    I would recomend logging in with a webclient and finding out how the page you are accessing is setting up its session. If it is in fact a cookie - you will need to first log in - and then in every subsequent call, add the cookie to the header of your request.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion