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