从 MemoryStream 中获取字符串的方法取决于字符串的编码方式。以下是使用不同编码方式从 MemoryStream 中获取字符串的方法:
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream, Encoding.ASCII);
writer.Write("Hello, world!");
writer.Flush();
memoryStream.Position = 0;
StreamReader reader = new StreamReader(memoryStream, Encoding.ASCII);
string result = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream, Encoding.UTF8);
writer.Write("你好,世界!");
writer.Flush();
memoryStream.Position = 0;
StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8);
string result = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream, Encoding.Unicode);
writer.Write("你好,世界!");
writer.Flush();
memoryStream.Position = 0;
StreamReader reader = new StreamReader(memoryStream, Encoding.Unicode);
string result = reader.ReadToEnd();
请注意,在使用完 StreamReader 和 MemoryStream 对象后,需要释放资源。可以使用 using
语句来实现资源的自动释放。
领取专属 10元无门槛券
手把手带您无忧上云