C# 文件与字节数组Bytes[]之间相互转换

 

C# 文件与字节数组Bytes[]之间相互转换

using System.IO;
 
namespace FileBytes
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = FileToBytes(@"D:\1.txt");
            if (bytes.Length > 0)
            {
                // 重新保存一份文件
                BytesToFile(bytes, @"D:\2.txt");
            }
 
            // 文件重新保存md5, sha1不变
        }
 
        /// <summary>
        /// 文件 -> Bytes
        /// </summary>
        /// <param name="path">指定路径文件</param>
        /// <returns>返回Stream</returns>
        public static byte[] FileToBytes(string path)
        {
            try
            {
                if (!System.IO.File.Exists(path)) { return new byte[0]; }
 
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    // 读取文件的 byte[]
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    return bytes;
                }
            }
            catch
            {
                throw;
            }
        }
 
        /// <summary>
        /// Bytes -> 文件
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <param name="path">保存地址</param>
        public static void BytesToFile(byte[] bytes, string path)
        {
            try
            {
                // 文件存在则删除
                if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); }
 
                // 写入文件,方式一
                using (FileStream fs = new FileStream(path, FileMode.CreateNew))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        bw.Write(bytes, 0, bytes.Length);
                    }
                }
 
                // 写入文件,方式二
                //System.IO.File.WriteAllBytes(path, bytes);
            }
            catch
            {
                throw;
            }
        }
    }
}

 

posted on 2022-02-15 08:37  funiyi816  阅读(1112)  评论(0编辑  收藏  举报

导航