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

 

一. 二进制转换成图片
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
Image img = Image.FromStream(ms);
ms.Close();
this.pictureBox1.Image

二. C#中byte[]与string的转换代码

1、System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
  byte[] inputBytes =converter.GetBytes(inputString);
  string inputString = converter.GetString(inputBytes);

2、string inputString = System.Convert.ToBase64String(inputBytes);
  byte[] inputBytes = System.Convert.FromBase64String(inputString);
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

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

/// 将 Stream 转成 byte[]

public byte[] StreamToBytes(Stream stream)
{
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
    // 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);
    return bytes;
}

/// 将 byte[] 转成 Stream

public Stream BytesToStream(byte[] bytes)
{
    Stream stream = new MemoryStream(bytes);
    return stream;
}

四. Stream 和 文件之间的转换

将 Stream 写入文件

public void StreamToFile(Stream stream,string fileName)
{
    // 把 Stream 转换成 byte[]
    byte[] bytes = new byte[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();
}

五. 从文件读取 Stream

public Stream FileToStream(string fileName)
{            
    // 打开文件
    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    // 读取文件的 byte[]
    byte[] bytes = new byte[fileStream.Length];
    fileStream.Read(bytes, 0, bytes.Length);
    fileStream.Close();
    // 把 byte[] 转换成 Stream
    Stream stream = new MemoryStream(bytes);
    return stream;
}

最新文章

  1. Perl语言
  2. grunt使用入门(zz)
  3. max_flow(Dinic) 分类: ACM TYPE 2014-09-02 15:42 94人阅读 评论(0) 收藏
  4. Win7中使用Eclipse连接虚拟机中的Ubuntu中的Hadoop2.4<3>
  5. 《iptables详解 》RHEL6
  6. Cookie禁用 获取session
  7. unix下快速混淆源代码
  8. Snapde和Excel、PowerPivot、WPS打开超大CSV文件性能比较
  9. Python测试模块doctest
  10. JavaScript 判断当前设备是否是移动端还是PC
  11. D - Mayor's posters(线段树+离散化)
  12. subline 建立服务器
  13. vue-lazyload 图片依赖加载
  14. 在DOS中操作MySQL数据库出现中文乱码
  15. PAT 1038 统计同成绩学生
  16. C# Redis 切换数据库
  17. SIFT(Scale-invariant feature transform) & HOG(histogram of oriented gradients)
  18. [leetcode]Clone Graph @ Python
  19. json list数据递归生成树状层级JSON
  20. springboot配置多数据源mongodb

热门文章

  1. css文本格式详解
  2. 关于Linux与windows传递文件乱码问题
  3. 学习 HTML5-目录
  4. 学习 zookeeper
  5. MVC中使用SignaIR入门教程
  6. FTP远程文件传输命令
  7. UNABLE TO PURGE A RECORD(二)
  8. 编写Java应用程序,定义Animal类,此类中有动物的属性:名称 name,腿的数量legs,统计动物的数量 count;方法:设置动物腿数量的方法 void setLegs(),获得腿数量的方法 getLegs(),设置动物名称的方法 setKind(),获得动物名称的方法 getKind(),获得动物数量的方法 getCount()。定义Fish类,是Animal类的子类,统计鱼的数量 co
  9. java:comp/env/jdbc/ 的两种配置方法
  10. PHP用mb_string函数库处理与windows相关中文字符