2014-04-02 183 views
4

我試圖將從richeditDocument生成的內存流轉換爲字節數組。代碼如下:在VB.Net中將MemoryStream轉換爲Byte Array

Public Sub saveAsTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) 

    Dim ms As MemoryStream = New MemoryStream() 
    richEditControl1.SaveDocument(ms, DocumentFormat.Rtf) 
    GetStreamAsByteArray(ms) 

    MessageBox.Show("save") 

End Sub 

Private Function GetStreamAsByteArray(ByVal stream As MemoryStream) As Byte() 

    Dim streamLength As Integer = Convert.ToInt32(stream.Length) 

    Dim fileData As Byte() = New Byte(streamLength) {} 

    ' Read the file into a byte array 
    stream.Read(fileData, 0, streamLength) 
    stream.Flush() 
    stream.Close() 

    Return fileData 

End Function 

流生成,因爲我可以得到流的長度,但最終的咬合數組只包含0使其無效。我怎樣才能得到正確的字節數組呢?

回答

6

如果你想從內存流中讀取,你需要確保流的當前位置是在開始。

此外,您正在使用Read方法錯誤。它返回讀取的字節數,可能少於請求的字節數。要正確使用它,您需要循環,直到獲得流中的所有字節。

然而,你應該只使用ToArray方法來獲取流中的一切作爲一個字節數組:

Private Function GetStreamAsByteArray(ByVal stream As MemoryStream) As Byte() 

    Return stream.ToArray() 

End Function 
0

「這對我的作品有100MB的.txt文件

Public Function read() 

    Dim tmpdb(0) As String 

    Try 

     tmpdb = IO.File.ReadAllLines("C:\Users\Admin01\Desktop\TmpTxt.txt") 
     FileOpen(1, "C:\Users\Admin01\Desktop\IRSH_TEST_DB.jrdb", OpenMode.Binary, OpenAccess.Write) 
     FilePut(1, tmpdb) 
     FileClose(1) 

     MessageBox.Show("SUCCES!") 

    Catch ex As Exception 
     MessageBox.Show(ex.Message) 
    End Try 

End Function 
相關問題