Luca F.
Luca F.

Reputation: 113

REST WebService: how to get zip file from web service to a client

I'm trying to create a function to download a zip file made ​​available from a REST WebService with a client that calls the Web Service(both written in VB.Net). WebService side I have the following code:

Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
    Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
    Dim length As Integer = CType(f.Length, Integer)
    WebOperationContext.Current.OutgoingResponse.ContentLength = length
    Dim buffer As Byte() = New Byte(length) {}
    Dim sum As Integer = 0
    Dim count As Integer
    While ((count = f.Read(buffer, sum, length - sum)) > 0)
        sum += count
    End While
    f.Close()
    Dim mimeType = ""
    WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
    Return New MemoryStream(buffer)
End Function

Client side I have the following code:

sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False

Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())

Response has ContentLenght = 242699, so seems to receive the stream, but StIn seems to be empty. What is the best solution to solve the problem?

Upvotes: 1

Views: 1250

Answers (1)

user3765589
user3765589

Reputation: 21

I think you've forgot to read from the StreamReader to the file.

        Dim inSaveFile As String = "C:\stream\test.doc"

        If Dir(inSaveFile) <> vbNullString Then
            Kill(inSaveFile)
        End If

        Dim swFile As System.IO.StreamWriter

        Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)

        swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)

        Dim response1 As System.Net.HttpWebResponse = req.GetResponse()

        Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)

        Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)

        swFile.WriteLine(stIn.ReadToEnd)

        swFile.Close()

        fs.Close()

Upvotes: 2

Related Questions