知识在于积累(.NET之路……)

导航

文件、Stream、byte[]之间的转换

private byte[] StreamToByte(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        /// 文件转换为数据流
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>数据流</returns>
        public FileStream FileConvertFileStream(string filePath)
        {
            System.IO.FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, System.IO.FileMode.Open);
            }
            catch
            {
            }
            fs.Close();
            return fs;
        }

        /// <summary>
        /// 文件转换二进制数据(用于保存数据库)
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>二进制</returns>
        public byte[] FileConvertByte(string filePath)
        {
            byte[] bytContent = null;
            System.IO.FileStream fs = null;
            System.IO.BinaryReader br = null;
            try
            {
                fs = new FileStream(filePath, System.IO.FileMode.Open);
            }
            catch
            {
            }
            br = new BinaryReader((Stream)fs);
            bytContent = br.ReadBytes((Int32)fs.Length);
            br.Close();
            fs.Close();
            return bytContent;
        }

 

posted on 2013-04-03 10:26  汤尼  阅读(163)  评论(0编辑  收藏  举报