c#常用工具类:文件和二进制转换

 //================二进制相关转换类==============
 
        #region 将文件转换为二进制数组
        /// <summary>
        /// 将文件转换为二进制数组
        /// </summary>
        /// <param name="FilePath">文件完整路径</param>
        /// <returns>二进制数组</returns>
        public static byte[] FileToBinary(string FilePath)
        {
            byte[] Buffer = null;
            if (Utils.FilesHelper.FileExists(FilePath) && System.IO.Path.HasExtension(FilePath))
            {
                FileStream stream = new FileInfo(FilePath).OpenRead();
                Buffer = new byte[stream.Length];
                stream.Read(Buffer, 0, Convert.ToInt32(stream.Length));
            }
            return Buffer;
        }
        #endregion
 
        #region 二进制数组转为文件
        /// <summary>
        /// 二进制数组转为文件
        /// </summary>
        /// <param name="FilePath">转到的文件完整路径</param>
        /// <param name="Buffer">二进制数组</param>
        /// <returns>转换是否成功</returns>
        public static bool BinaryToFile(string FilePath, byte[] Buffer)
        {
            bool flag = false;
            FileStream fstream = File.Create(FilePath, Buffer.Length);
            try
            {               
                fstream.Write(Buffer, 0, Buffer.Length);
                flag = true;
            }
            catch (Exception)
            {
            }
            finally
            {
                fstream.Close();
            }
            return flag;
        }
        #endregion

  

posted @ 2014-08-16 09:43  跟着阿笨一起玩.NET  阅读(854)  评论(0编辑  收藏  举报