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

作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角