首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# Stream 和 byte[] 之间的转换

C# Stream 和 byte[] 之间的转换

作者头像
跟着阿笨一起玩NET
发布2018-09-18 15:19:43
1.4K0
发布2018-09-18 15:19:43
举报
/* - - - - - - - - - - - - - - - - - - - - - - - - 
 * Stream 和 byte[] 之间的转换
 * - - - - - - - - - - - - - - - - - - - - - - - */
///<summary>
/// 将 Stream 转成 byte[]
///</summary>
publicbyte[] StreamToBytes(Stream stream)
{
byte[] bytes =newbyte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
///<summary>
/// 将 byte[] 转成 Stream
///</summary>
public Stream BytesToStream(byte[] bytes)
{
    Stream stream =new MemoryStream(bytes);
return stream;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - 
 * Stream 和 文件之间的转换
 * - - - - - - - - - - - - - - - - - - - - - - - */
///<summary>
/// 将 Stream 写入文件
///</summary>
publicvoid StreamToFile(Stream stream,string fileName)
{
// 把 Stream 转换成 byte[]
byte[] bytes =newbyte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);
// 把 byte[] 写入文件
    FileStream fs =new FileStream(fileName, FileMode.Create);
    BinaryWriter bw =new BinaryWriter(fs);
    bw.Write(bytes);
    bw.Close();
    fs.Close();
}
///<summary>
/// 从文件读取 Stream
///</summary>
public Stream FileToStream(string fileName)
{            
// 打开文件
    FileStream fileStream =new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
byte[] bytes =newbyte[fileStream.Length];
    fileStream.Read(bytes, 0, bytes.Length);
    fileStream.Close();
// 把 byte[] 转换成 Stream
    Stream stream =new MemoryStream(bytes);
return stream;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-06-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档