将字节数组转换为流

Posted

技术标签:

【中文标题】将字节数组转换为流【英文标题】:Converting a bytes array to stream [duplicate] 【发布时间】:2014-11-08 01:38:29 【问题描述】:

有没有办法将从 sql server 返回的字节数组转换为 c# 中的流对象? 我希望能够在下面做这样的事情

FileStream fs = new FileStream(@"C:\Users\sample\sample\sample.txt", FileMode.Open, FileAccess.Read);
fs.Seek(0, SeekOrigin.Begin);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//bytes array will be saved in the database
//The following will be returned from the database and i need it to be in a stream
Stream s = (Stream)bytes;

除了 varbinary(MAX) 格式之外,还有其他方法可以将其保存在 sql server 中吗?

【问题讨论】:

【参考方案1】:

这很容易。只需使用MemoryStream 转换即可。

Stream S = new MemoryStream(bytes);

或者这个。

    static void Write(Stream s, Byte[] bytes)
    
        using (var writer = new BinaryWriter(s))
        
            writer.Write(bytes);
        
    

【讨论】:

【参考方案2】:

您可以使用MemoryStream 类将字节数组转换为Stream 对象

Stream st = new MemoryStream(bytes);

【讨论】:

以上是关于将字节数组转换为流的主要内容,如果未能解决你的问题,请参考以下文章