I am connecting to a web site using HttpWebRequest, and opening a file url, which is actually a MS word doc.I need to download the same through backend, but the file, on downloading, is getting corrupted.I think the problem is with the encoding.Here is how i am doing it:
Dim wReq as HttpWebRequest
Dim wResp as HttpWebResponse
Dim str as String
Dim sr as StreamReader
Dim sw as StreamWriter
wReq = CType(WebRequest.Create(New Uri(strURL)),HttpWebRequest)
wReq.Method = "POST"
wReq.KeepAlive = True
wReq.Credentials = New NetworkCredential(user, passwd, domain)
wReq.ContentType = "application/msword"
wResp = wReq.GetResponse
sr = New StreamReader(wResp.GetResponseStream, System.Text.Encoding.ASCII)
str = sr.ReadToEnd.Trim
sr.Close()
wResp.Close()
wReq = Nothing
If
Not str Is Nothing And str.Length > 0 Thensw =
New StreamWriter(dFolder & filename & "." & "doc", False)sw.WriteLine(txt)
sw.Close()
sw = Nothing
End If
Please note i have to use http Web request only since the site throws up a login page which i am bypassing by posting parameters.
Please help.
Thanks in advance!
Scott LyslePosted Nov 14, 2006, 4:30 PM
Three button handlers setting a doc file, a txt file, and an image file path and passing that as a string to a subroutine called Download:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Download(
"~\documents\Isherwood.doc") End Sub Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.ClickDownload(
"~\documents\Isherwood.txt") End Sub Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.ClickDownload(
"~\documents\USS Isherwood 2.jpg") End SubThe subroutine that manages the download:
Public Sub Download(ByVal strPath As String) Dim fileName As String = strPath If Not String.IsNullOrEmpty(fileName) Then
fileName = Server.MapPath(fileName)
Dim fi As System.IO.FileInfofi =
New System.IO.FileInfo(fileName) If fi.Exists ThenResponse.Clear()
Response.AddHeader(
"Content-Disposition", "attachment; filename=" & fi.Name)Response.AddHeader(
"Content-Length", fi.Length.ToString())Response.ContentType =
"application/octet-stream"Response.WriteFile(fi.FullName)
Response.End()
ElseResponse.Write(
"No such file") End If End If End Sub