zoukankan      html  css  js  c++  java
  • C#:文件、byte[]、Stream相互转换

    一、byte[] 和 Stream

            /// <summary>
            /// byte[]转换成Stream
            /// </summary>
            /// <param name="bytes"></param>
            /// <returns></returns>
            public Stream BytesToStream(byte[] bytes)
            {
                Stream stream = new MemoryStream(bytes);
                return stream;
            }
    
            /// <summary>
            /// Stream转换成byte[]
            /// </summary>
            /// <param name="stream"></param>
            /// <returns></returns>
            public byte[] StreamToBytes(Stream stream)
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin); // 设置当前流的位置为流的开始
                return bytes;
            }
    

    二、文件 和 Stream

            /// <summary>
            /// 从文件读取Stream
            /// </summary>
            /// <param name="path"></param>
            /// <returns></returns>
            public Stream FileToStream(string path)
            {
                FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); // 打开文件
                byte[] bytes = new byte[fileStream.Length]; // 读取文件的byte[]
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();
                Stream stream = new MemoryStream(bytes); // 把byte[]转换成Stream
                return stream;
            }
    
            /// <summary>
            /// 将Stream写入文件
            /// </summary>
            /// <param name="stream"></param>
            /// <param name="path"></param>
            public void StreamToFile(Stream stream, string path)
            {
                byte[] bytes = new byte[stream.Length]; // 把Stream转换成byte[]
                stream.Read(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin); // 设置当前流的位置为流的开始
                FileStream fs = new FileStream(path, FileMode.Create); // 把byte[]写入文件
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(bytes);
                bw.Close();
                fs.Close();
            }
    

    转自:http://www.cnblogs.com/warioland/archive/2012/03/06/2381355.html

  • 相关阅读:
    [BZOJ1659][Usaco2006 Mar]Lights Out 关灯
    [BZOJ1789][BZOJ1830][Ahoi2008]Necklace Y型项链
    [HDU5015]233 Matrix
    [BZOJ1786][BZOJ1831]逆序对
    各种音视频编解码学习详解
    Methods and systems for sharing common job information
    在nodejs使用Redis缓存和查询数据及Session持久化(Express)
    jQuery 遍历 – 同胞(siblings)
    jQuery 遍历 – 后代
    jQuery 遍历 – 祖先
  • 原文地址:https://www.cnblogs.com/Cchblogs/p/6946709.html
Copyright © 2011-2022 走看看