C#:文件、byte[]、Stream相互轉換

1、byte[] 和 Streamhtml

        /// <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;
        }

2、文件 和 Streamhtm

        /// <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.htmlblog

相關文章
相關標籤/搜索