.net - 如何从 MemoryStream 中获取字符串?

标签 .net vb.net string memorystream

如果给我一个 MemoryStream,我知道它已填充了 String,我如何取回 String

最佳答案

此示例演示如何读取字符串并将其写入 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

关于.net - 如何从 MemoryStream 中获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/78181/

相关文章:

c# - 你什么时候会实现自己的排序算法?

javascript - 我的正则表达式搞砸了我其余的 javascript

JavaScript 原语

C++判断硬盘剩余空间

c# - 如何在 app.config 文件中转义 [?

c# - 具有可变数量的 TextBlock(使用 ItemsControl 创建)的 WPF RichTextBox 失去选择行为

c# - 在代码隐藏中设置 Eval

.net - 计算文本框中的换行数

database - 如何在 VB.Net 中使用数据库查询创建 Excel 文件?

java - 如何在 java 中查找字符串中的 EOF?