1. 程式人生 > >C#檔案轉換為byte陣列,byte陣列轉換為檔案並儲存到指定地址

C#檔案轉換為byte陣列,byte陣列轉換為檔案並儲存到指定地址

 /// <summary>
        /// 將檔案轉換為byte陣列
        /// </summary>
        /// <param name="path">檔案地址</param>
        /// <returns>轉換後的byte陣列</returns>
        public static byte[] File2Bytes(string path) {
            if (!System.IO.File.Exists(path)) {
                return new byte[0];
            }

            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];

            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            return buff;
        }

        /// <summary>
        /// 將byte陣列轉換為檔案並儲存到指定地址
        /// </summary>
        /// <param name="buff">byte陣列</param>
        /// <param name="savepath">儲存地址</param>
        public static void Bytes2File(byte[] buff, string savepath, string fileName) {
            try {

                //如果不存在就建立Enclosure資料夾 
                if (Directory.Exists(savepath + @"\Enclosure\") == false) {
                    Directory.CreateDirectory(savepath + @"\Enclosure\");
                }

                if (System.IO.File.Exists(savepath + @"\Enclosure\" + fileName)) {
                    System.IO.File.Delete(savepath + @"\Enclosure\" + fileName);
                }
                //建立Process命令
                var cmd = new Process();
                FileStream fs = new FileStream(savepath + @"\Enclosure\" + fileName, FileMode.CreateNew);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(buff, 0, buff.Length);
                bw.Close();
                fs.Close();
                //建立要執行的檔案或者程式
                var startfile = new ProcessStartInfo {
                    FileName = savepath + @"\Enclosure\" + fileName,//檔案完全路徑
                    WindowStyle = ProcessWindowStyle.Normal,//Windows視窗樣式
                    UseShellExecute = true//為true,則用預設的開啟方式開啟
                };
                cmd.StartInfo = startfile;
                cmd.Start(); //開啟檔案
            } catch (Exception) {

            }

        }