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 ,在此对作者表示感谢!

  • 相关阅读:
    多个相同结构的表的字段的修改、添加
    SQL SERVER 查询去重 PARTITION BY
    message from server: "Host 'xxx' is not allowed to connect to th
    jdk 1.8 连接数据库
    恢复SQLServer数据库后,如何同步登陆名和用户名
    无法识别的属性“targetFramework”。请注意属性名称区分大小写。错误解决办法
    jquery.tablesorter 使用
    MD5加密
    C# 判断是否是节假日
    word ladder
  • 原文地址:https://www.cnblogs.com/angleSJW/p/1776678.html
Copyright © 2011-2022 走看看