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) {

            }

        }

猜你喜欢

转载自blog.csdn.net/weixin_40316929/article/details/85618105
今日推荐