zoukankan      html  css  js  c++  java
  • Stream 和Byte[] 之间的转换

    代码
     1 //Stream 和Byte[]之间的转换
     2 byte[] arr=new byte[stream.Length];//设定arr长度
     3 
     4 stream.Read(arr,0,arr.Length);//stream从arr中读取数据
     5 
     6 //提供表示流中的参考点以供进行查找的字段,设置当前流中的位置。
     7 stream.Seek(0,SeekOrigin.Begin);
     8  
     9 return arr;
    10 
    11 
    12 //将byte[] 转换成Stream 利用内存
    13 Stream stream=new MemoryStream(arr);
    14 return stream;
    15 
    16 /* - - - - - - - - - - - - - - - - - - - - - - - - 
    17  * Stream 和 文件之间的转换
    18  * - - - - - - - - - - - - - - - - - - - - - - - */
    19 /// <summary>
    20 /// 将 Stream 写入文件
    21 /// </summary>
    22 public void StreamToFile(Stream stream,string fileName)
    23 {
    24     // 把 Stream 转换成 byte[]
    25     byte[] bytes = new byte[stream.Length];
    26     stream.Read(bytes, 0, bytes.Length);
    27     // 设置当前流的位置为流的开始
    28     stream.Seek(0, SeekOrigin.Begin);
    29 
    30     // 把 byte[] 写入文件
    31     FileStream fs = new FileStream(fileName, FileMode.Create);
    32     BinaryWriter bw = new BinaryWriter(fs);
    33     bw.Write(bytes);
    34     bw.Close();
    35     fs.Close();
    36 }
    37 
    38 /// <summary>
    39 /// 从文件读取 Stream
    40 /// </summary>
    41 public Stream FileToStream(string fileName)
    42 {            
    43     // 打开文件
    44     FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    45     // 读取文件的 byte[]
    46     byte[] bytes = new byte[fileStream.Length];
    47     fileStream.Read(bytes, 0, bytes.Length);
    48     fileStream.Close();
    49     // 把 byte[] 转换成 Stream
    50     Stream stream = new MemoryStream(bytes);
    51     return stream;
    52 }

      文章参考:http://www.cnblogs.com/anjou/archive/2007/12/07/986887.html?login=1#commentform ,在此对作者表示感谢!

  • 相关阅读:
    结对编程项目作业4
    团队编程项目进度
    团队编程项目作业2-团队编程项目代码设计规范
    现代软件工程 阅读笔记
    个人编程作业1-GIT应用
    结对编程项目作业2-开发环境搭建过程
    结对编程项目作业2-结对编项目设计文档
    课后作业-阅读任务-阅读提问
    《团队-科学计算器-模块测试过程》
    团队-科学计算器-模块开发过程
  • 原文地址:https://www.cnblogs.com/angleSJW/p/1776678.html
Copyright © 2011-2022 走看看