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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM