2014-02-05 99 views
2

我有一個網絡REST服務,我試圖從中提取圖像(或wav文件)。 我可以通過內存流獲取圖像(jpg)並將其顯示到圖片框,然後將圖片框保存到文件中。 我想要做的是消除使用圖片框的中間步驟,並將內存流直接保存到文件。但是,生成的文件似乎不是一個jpg文件。 打開時會拋出損壞的文件錯誤。vb.net將網絡二進制文件保存到文件

我的代碼如下:

 Dim msgURI As String 
     msgURI = "http://192.168.0.1/attachment/12345/0" 

     Dim Pic As New PictureBox() 

     Dim web_client As New WebClient() 
     web_client.Credentials = New NetworkCredential("XX", "XX") 
     Dim image_stream As New MemoryStream(web_client.DownloadData(msgURI)) 
     Pic.Image = Image.FromStream(image_stream) 


     Dim bm As Bitmap = Pic.Image 
     Dim filename As String = "c:\temp\test.jpg" 
     bm.Save(filename, Imaging.ImageFormat.Jpeg) 

和工作正常。

然而,當我使用以下方法來繞過位圖和圖片框:

 Using file As New FileStream(filename, FileMode.Create, System.IO.FileAccess.Write) 
      Dim bytes As Byte() = New Byte(image_stream.Length - 1) {} 
      image_stream.Read(bytes, 0, CInt(image_stream.Length)) 
      file.Write(bytes, 0, bytes.Length) 
      image_stream.Close() 
     End Using 

我得到一個文件,它是一個已損壞的JPG文件。

任何幫助,非常感謝。

特里

回答

0

WebClient.DownloadData方法返回一個字節數組。因此,將字節數組加載到內存流中似乎非常愚蠢,只是爲了將其再次讀入另一個字節數組中,然後將其保存到文件中。所有這一切都可以很容易地通過直接從第一字節數組將一個文件來完成,像這樣:

File.WriteAllBytes("c:\temp\test.jpg", web_client.DownloadData(msgURI)) 

然而,即使是低效率的,因爲你可以直接從網絡流中的數據文件,如這個:

web_client.DownloadFile(msgURI, "c:\temp\test.jpg")