你如何从一个MemoryStream获得一个字符串?

  • 回答 (2)
  • 关注 (0)
  • 查看 (157)

如果我有一个MemoryStream,我已经知道已经填充了一个字符串,我怎么得到这一个字符串?

小川小川提问于
秋之夕颜清念念不忘,必有回响回答于

你也可以使用

Encoding.ASCII.GetString(ms.ToArray());

我不认为这是有效的,但我不能发誓。它也可以让你选择不同的编码,而使用StreamReader你必须指定它作为参数。

MyLove回答于

此示例显示如何读取和写入一个字符串到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

所属标签

可能回答问题的人

  • 西风

    renzha.net · 站长 (已认证)

    7 粉丝1 提问9 回答
  • 四无君

    0 粉丝0 提问3 回答
  • 旺仔小小鹿

    社区 · 运营 (已认证)

    46 粉丝0 提问2 回答
  • 拉布拉多拉不多

    1 粉丝0 提问2 回答

扫码关注云+社区

领取腾讯云代金券