加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:35:49 所属栏目:百科 来源:网络整理
导读:如果我得到一个MemoryStream,我知道已填充一个字符串,我如何得到一个字符串退出? 此示例显示如何读取和写入一个字符串到MemoryStream。 static void Main(string[] args){ using (var ms = new MemoryStream()) { var sw = new StreamWriter(ms); sw.Writ
如果我得到一个MemoryStream,我知道已填充一个字符串,我如何得到一个字符串退出?
此示例显示如何读取和写入一个字符串到MemoryStream。
static void Main(string[] args)
{
    using (var ms = new MemoryStream())
    {
        var sw = 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
        //DON'T DO THIS - 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;
        var sr = new StreamReader(ms);
        var myStr = sr.ReadToEnd();
        Console.WriteLine(myStr);
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读