我们如何从MemoryStream获取字符串?
时间:2020-03-05 18:57:27 来源:igfitidea点击:
如果给我一个我知道已经被一个String填充的MemoryStream,我该如何退回一个String呢?
解决方案
回答
使用StreamReader,然后可以使用返回字符串的ReadToEnd方法。
回答
使用StreamReader将MemoryStream转换为字符串。
<Extension()> _ Public Function ReadAll(ByVal memStream As MemoryStream) As String ' Reset the stream otherwise you will just get an empty string. ' Remember the position so we can restore it later. Dim pos = memStream.Position memStream.Position = 0 Dim reader As New StreamReader(memStream) Dim str = reader.ReadToEnd() ' Reset the position so that subsequent writes are correct. memStream.Position = pos Return str End Function
回答
此示例说明如何向MemoryStream读取和写入字符串。
Imports System.IO Module Module1 Sub Main() ' We don't need to dispose any of the MemoryStream ' because it is a managed object. However, just for ' good practice, we'll close the MemoryStream. Using ms As New MemoryStream Dim sw As New StreamWriter(ms) sw.WriteLine("Hello World") ' The string is currently stored in the ' StreamWriters buffer. Flushing the stream will ' force the string into the MemoryStream. sw.Flush() ' If we dispose the StreamWriter now, it will close ' the BaseStream (which is our MemoryStream) which ' will prevent us from reading from our MemoryStream 'sw.Dispose() ' The StreamReader will read from the current ' position of the MemoryStream which is currently ' set at the end of the string we just wrote to it. ' We need to set the position to 0 in order to read ' from the beginning. ms.Position = 0 Dim sr As New StreamReader(ms) Dim myStr = sr.ReadToEnd() Console.WriteLine(myStr) ' We can dispose our StreamWriter and StreamReader ' now, though this isn't necessary (they don't hold ' any resources open on their own). sw.Dispose() sr.Dispose() End Using Console.WriteLine("Press any key to continue.") Console.ReadKey() End Sub End Module
回答
我们也可以使用
Encoding.ASCII.GetString(ms.ToArray());
我认为这样做效率不高,但我不能对此宣誓。它还允许我们选择其他编码,而使用StreamReader则必须将其指定为参数。
回答
稍作修改的Brian答案允许对读开始进行可选管理,这似乎是最简单的方法。可能不是最有效的,但易于理解和使用。
Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String ' reset the stream or we'll get an empty string returned ' remember the position so we can restore it later Dim Pos = memStream.Position memStream.Position = startPos Dim reader As New StreamReader(memStream) Dim str = reader.ReadToEnd() ' reset the position so that subsequent writes are correct memStream.Position = Pos Return str End Function