C#文件加密方法汇总

方法一(已实测)

一、加解密文件

1.指定加解密保存文件路径方法,该方法保留源文件

        /// <summary>
        /// 文件加密
        /// </summary>
        /// <param name="inputFile">要加密的文件路径</param>
        /// <param name="outputFile">加密后的文件存放路径</param>
        public static void EncryptFile(string inputFile, string outputFile)   //加密
        {
            try
            {
                string password = @"12345678";
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                string cryptFile = outputFile;
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);

                FileStream fsIn = new FileStream(inputFile, FileMode.Open);

                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);


                fsIn.Close();
                cs.Close();
                fsCrypt.Close();


                MessageBox.Show("Encrypt Source file succeed!", "Msg :");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Source file error!", "Error :");
            }
        }

        /// <summary>
        /// 文件解密
        /// </summary>
        /// <param name="inputFile">要解密的文件路径</param>
        /// <param name="outputFile">解密后的文件存放路径</param>
        public static void DecryptFile(string inputFile, string outputFile)   //解密
        {
            try
            {
                string password = @"12345678";
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                FileStream fsOut = new FileStream(outputFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

                MessageBox.Show("Decrypt Source file succeed!", "Msg :");

            }
            catch (Exception ex)
            {
                MessageBox.Show("Source file error", "Error :");
            }
        }
View Code

2.加解密后直接覆盖原文件

        /// <summary>
        /// 自定义文件后缀枚举
        /// </summary>
        public enum FileSuffix
        {
            /// <summary>
            /// 文本后缀
            /// </summary>
            Txt,
            /// <summary>
            /// 配置文件后缀
            /// </summary>
            Ini,
            /// <summary>
            /// 图片png后缀
            /// </summary>
            Png,
            /// <summary>
            /// 图片jpg后缀
            /// </summary>
            Jpg,
            /// <summary>
            /// 图片bmp后缀
            /// </summary>
            Bmp
        }
        /// <summary>
        /// 自定义文件后缀对应后缀内容
        /// </summary>
        private static Dictionary<FileSuffix, string> FileSuffixDic = new Dictionary<FileSuffix, string>()
        {
            { FileSuffix.Txt, ".txt" },
            { FileSuffix.Ini, ".ini" },
            { FileSuffix.Png, ".png" },
            { FileSuffix.Jpg, ".jpg" },
            { FileSuffix.Bmp, ".bmp" },
        };

        /// <summary>
        /// 文件加密
        /// </summary>
        /// <param name="inputFile">要加密文件的文件路径</param>
        /// <param name="password">加密密码</param>
        /// <param name="fileSuffix">加密文件的后缀(以加密文件类型来决定)</param>
        /// <returns>加密成功返回true,失败或异常返回false</returns>
        public static bool EncryptFile(string inputFile, string password, FileSuffix fileSuffix)   //加密
        {
            string cryptFile = @"C:\CacheFile" + FileSuffixDic[fileSuffix];
            FileStream fsCrypt = null;
            FileStream fsIn = null;
            CryptoStream cs = null;
            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                fsCrypt = new FileStream(cryptFile, FileMode.Create);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);

                fsIn = new FileStream(inputFile, FileMode.Open);
                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);

                fsIn.Close();
                cs.Close();
                fsCrypt.Close();

                File.Delete(inputFile);
                File.Move(cryptFile, inputFile);

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加密文件 " + inputFile + " 时发生异常!\r\n\r\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (fsCrypt != null) fsCrypt.Close();
                if (cs != null) fsCrypt.Close();
                if (fsIn != null) fsCrypt.Close();
                return false;
            }
        }

        /// <summary>
        /// 文件解密
        /// </summary>
        /// <param name="inputFile">要解密文件的文件路径</param>
        /// <param name="password">解密密码(要与加密密码相同)</param>
        /// <param name="fileSuffix">解密文件的后缀(以解密文件类型来决定)</param>
        /// <returns>解密成功返回true,失败或异常返回false</returns>
        public static bool DecryptFile(string inputFile, string password, FileSuffix fileSuffix)   //解密
        {
            FileStream fsCrypt = null;
            CryptoStream cs = null;
            FileStream fsOut = null;
            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                fsCrypt = new FileStream(inputFile, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                fsOut = new FileStream(@"C:\CacheFile" + FileSuffixDic[fileSuffix], FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

                File.Delete(inputFile);
                File.Move(@"C:\CacheFile" + FileSuffixDic[fileSuffix], inputFile);

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("解密文件 " + inputFile + " 时发生异常!\r\n\r\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (fsCrypt != null) fsCrypt.Close();
                if (cs != null) fsCrypt.Close();
                if (fsOut != null) fsCrypt.Close();
                return false;
            }
        }
View Code

 

 

方法二(以下方式实用性并未证实,用于借鉴)

使用引用

using System.IO;
using System.Security.Cryptography;

 

一、加解密字符串及字节数组

1.加密

        #region 加密
        #region 加密字符串
        /// <summary>
        /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥</param>
        public static string AESEncrypt(string EncryptString, string EncryptKey)
        {
           return Convert.ToBase64String(Encoding.Default.GetBytes(AESEncrypt(EncryptString, EncryptKey)));
        }

        #endregion

        #region 加密字节数组
        /// <summary>
        /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥</param>
        public static byte[] AESEncrypt(byte[] EncryptByte, string EncryptKey)
        {
            if (EncryptByte.Length == 0) { throw (new Exception("明文不得为空")); }
            if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
            byte[] m_strEncrypt;
            byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
            byte[] m_salt = Convert.FromBase64String("gsf4jvkyhye5/d7k8OrLgM==");
            Rijndael m_AESProvider = Rijndael.Create();
            try
            {
                MemoryStream m_stream = new MemoryStream();
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(EncryptKey, m_salt);
                ICryptoTransform transform = m_AESProvider.CreateEncryptor(pdb.GetBytes(32), m_btIV);
                CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
                m_csstream.Write(EncryptByte, 0, EncryptByte.Length);
                m_csstream.FlushFinalBlock();
                m_strEncrypt = m_stream.ToArray();
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }
            return m_strEncrypt;
        }
        #endregion
        #endregion
View Code

2.解密

        #region 解密
        #region 解密字符串
        /// <summary>
        /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥</param>
        public static string AESEncrypt(string EncryptString, string EncryptKey)
        {
            return Convert.ToBase64String(Encoding.Default.GetBytes(AESEncrypt(EncryptString, EncryptKey)));
        }
        #endregion

        #region 解密字节数组
        /// <summary>
        /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey">解密密钥</param>
        public static byte[] AESDecrypt(byte[] DecryptByte, string DecryptKey)
        {
            if (DecryptByte.Length == 0) { throw (new Exception("密文不得为空")); }
            if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
            byte[] m_strDecrypt;
            byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
            byte[] m_salt = Convert.FromBase64String("gsf4jvkyhye5/d7k8OrLgM==");
            Rijndael m_AESProvider = Rijndael.Create();
            try
            {
                MemoryStream m_stream = new MemoryStream();
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(DecryptKey, m_salt);
                ICryptoTransform transform = m_AESProvider.CreateDecryptor(pdb.GetBytes(32), m_btIV);
                CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
                m_csstream.Write(DecryptByte, 0, DecryptByte.Length);
                m_csstream.FlushFinalBlock();
                m_strDecrypt = m_stream.ToArray();
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }
            return m_strDecrypt;
        }
        #endregion
        #endregion
View Code

 

二、加解密文件

    /// <summary>
    /// 文件加密类
    /// </summary>
    public class FileEncrypt
    {
        #region 变量
        /// <summary>
        /// 一次处理的明文字节数
        /// </summary>
        public static readonly int encryptSize = 10000000;
        /// <summary>
        /// 一次处理的密文字节数
        /// </summary>
        public static readonly int decryptSize = 10000016;
        #endregion

        #region 加密文件
        /// <summary>
        /// 加密文件
        /// </summary>
        public static void EncryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress)
        {
            try
            {
                if (File.Exists(path + ".temp")) File.Delete(path + ".temp");
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    if (fs.Length > 0)
                    {
                        using (FileStream fsnew = new FileStream(path + ".temp", FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            if (File.Exists(path + ".temp")) File.SetAttributes(path + ".temp", FileAttributes.Hidden);
                            int blockCount = ((int)fs.Length - 1) / encryptSize + 1;
                            for (int i = 0; i < blockCount; i++)
                            {
                                int size = encryptSize;
                                if (i == blockCount - 1) size = (int)(fs.Length - i * encryptSize);
                                byte[] bArr = new byte[size];
                                fs.Read(bArr, 0, size);
                                byte[] result = AES.AESEncrypt(bArr, pwd);
                                fsnew.Write(result, 0, result.Length);
                                fsnew.Flush();
                                refreshFileProgress(blockCount, i + 1); //更新进度
                            }
                            fsnew.Close();
                            fsnew.Dispose();
                        }
                        fs.Close();
                        fs.Dispose();
                        FileAttributes fileAttr = File.GetAttributes(path);
                        File.SetAttributes(path, FileAttributes.Archive);
                        File.Delete(path);
                        File.Move(path + ".temp", path);
                        File.SetAttributes(path, fileAttr);
                    }
                }
            }
            catch (Exception ex)
            {
                File.Delete(path + ".temp");
                throw ex;
            }
        }
        #endregion

        #region 解密文件
        /// <summary>
        /// 解密文件
        /// </summary>
        public static void DecryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress)
        {
            try
            {
                if (File.Exists(path + ".temp")) File.Delete(path + ".temp");
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    if (fs.Length > 0)
                    {
                        using (FileStream fsnew = new FileStream(path + ".temp", FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            if (File.Exists(path + ".temp")) File.SetAttributes(path + ".temp", FileAttributes.Hidden);
                            int blockCount = ((int)fs.Length - 1) / decryptSize + 1;
                            for (int i = 0; i < blockCount; i++)
                            {
                                int size = decryptSize;
                                if (i == blockCount - 1) size = (int)(fs.Length - i * decryptSize);
                                byte[] bArr = new byte[size];
                                fs.Read(bArr, 0, size);
                                byte[] result = AES.AESDecrypt(bArr, pwd);
                                fsnew.Write(result, 0, result.Length);
                                fsnew.Flush();
                                refreshFileProgress(blockCount, i + 1); //更新进度
                            }
                            fsnew.Close();
                            fsnew.Dispose();
                        }
                        fs.Close();
                        fs.Dispose();
                        FileAttributes fileAttr = File.GetAttributes(path);
                        File.SetAttributes(path, FileAttributes.Archive);
                        File.Delete(path);
                        File.Move(path + ".temp", path);
                        File.SetAttributes(path, fileAttr);
                    }
                }
            }
            catch (Exception ex)
            {
                File.Delete(path + ".temp");
                throw ex;
            }
        }
        #endregion

    }

    /// <summary>
    /// 更新文件加密进度委托
    /// </summary>
    public delegate void RefreshFileProgress(int max, int value);
View Code

 

三、加解密文件夹

    /// <summary>
    /// 文件夹加密类
    /// </summary>
    public class DirectoryEncrypt
    {
        #region 加密文件夹及其子文件夹中的所有文件
        /// <summary>
        /// 加密文件夹及其子文件夹中的所有文件
        /// </summary>
        public static void EncryptDirectory(string dirPath, string pwd, RefreshDirProgress refreshDirProgress, RefreshFileProgress refreshFileProgress)
        {
            string[] filePaths = Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories);
            for (int i = 0; i < filePaths.Length; i++)
            {
                FileEncrypt.EncryptFile(filePaths[i], pwd, refreshFileProgress);
                refreshDirProgress(filePaths.Length, i + 1);
            }
        }
        #endregion

        #region 解密文件夹及其子文件夹中的所有文件
        /// <summary>
        /// 解密文件夹及其子文件夹中的所有文件
        /// </summary>
        public static void DecryptDirectory(string dirPath, string pwd, RefreshDirProgress refreshDirProgress, RefreshFileProgress refreshFileProgress)
        {
            string[] filePaths = Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories);
            for (int i = 0; i < filePaths.Length; i++)
            {
                FileEncrypt.DecryptFile(filePaths[i], pwd, refreshFileProgress);
                refreshDirProgress(filePaths.Length, i + 1);
            }
        }
        #endregion

    }

    /// <summary>
    /// 更新文件夹加密进度委托
    /// </summary>
    public delegate void RefreshDirProgress(int max, int value);
View Code

 

四、跨线程访问委托

    /// <summary>
    /// 跨线程访问控件的委托
    /// </summary>
    public delegate void InvokeDelegate();

    /// <summary>
    /// 跨线程访问控件类
    /// </summary>
    public class InvokeUtil
    {
        /// <summary>
        /// 跨线程访问控件
        /// </summary>
        /// <param name="ctrl">Form对象</param>
        /// <param name="de">委托</param>
        public static void Invoke(Control ctrl, Delegate de)
        {
            if (ctrl.IsHandleCreated)
            {
                ctrl.BeginInvoke(de);
            }
        }
    }
View Code

 

五、窗体调用加解密示例代码(不包含控件生成代码)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Utils;
using System.Threading;
using EncryptFile.Utils;
namespace EncryptFile
{
    public partial class Form1 : Form
    {
        #region 变量
        /// <summary>
        /// 一次处理的明文字节数
        /// </summary>
        public static int encryptSize = 10000000;
        /// <summary>
        /// 一次处理的密文字节数
        /// </summary>
        public static int decryptSize = 10000016;
        #endregion

        #region 构造函数
        public Form1()
        {
            InitializeComponent();
        }
        #endregion

        #region 加密文件
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            #region 验证
            if (txtPwd.Text == "")
            {
                MessageBox.Show("密码不能为空", "提示");
                return;
            }

            if (txtPwdCfm.Text == "")
            {
                MessageBox.Show("确认密码不能为空", "提示");
                return;
            }

            if (txtPwdCfm.Text != txtPwd.Text)
            {
                MessageBox.Show("两次输入的密码不相同", "提示");
                return;
            }
            #endregion

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            pbFile.Value = 0;
                            lblProgressFile.Text = "0%";
                            pbDir.Visible = false;
                            lblProgressDir.Visible = false;
                            pbFile.Visible = false;
                            lblProgressFile.Visible = false;
                            lblShowPath.Text = "文件:" + openFileDialog1.FileName;
                            lblShowPath.Visible = true;
                            DisableBtns();
                        };
                        InvokeUtil.Invoke(this, invokeDelegate);
                        DateTime t1 = DateTime.Now;
                        FileEncrypt.EncryptFile(openFileDialog1.FileName, txtPwd.Text, RefreshFileProgress);
                        DateTime t2 = DateTime.Now;
                        string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
                        if (MessageBox.Show("加密成功,耗时" + t + "", "提示") == DialogResult.OK)
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show("加密失败:" + ex.Message, "提示") == DialogResult.OK)
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                }));
                thread.Start();
            }
        }
        #endregion

        #region 解密文件
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            #region 验证
            if (txtPwd.Text == "")
            {
                MessageBox.Show("密码不能为空", "提示");
                return;
            }
            #endregion

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            pbFile.Value = 0;
                            lblProgressFile.Text = "0%";
                            pbDir.Visible = false;
                            lblProgressDir.Visible = false;
                            pbFile.Visible = false;
                            lblProgressFile.Visible = false;
                            lblShowPath.Text = "文件:" + openFileDialog1.FileName;
                            lblShowPath.Visible = true;
                            DisableBtns();
                        };
                        InvokeUtil.Invoke(this, invokeDelegate);
                        DateTime t1 = DateTime.Now;
                        FileEncrypt.DecryptFile(openFileDialog1.FileName, txtPwd.Text, RefreshFileProgress);
                        DateTime t2 = DateTime.Now;
                        string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
                        if (MessageBox.Show("解密成功,耗时" + t + "", "提示") == DialogResult.OK)
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show("解密失败:" + ex.Message, "提示") == DialogResult.OK)
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                }));
                thread.Start();
            }
        }
        #endregion

        #region 文件夹加密
        private void btnEncryptDir_Click(object sender, EventArgs e)
        {
            #region 验证
            if (txtPwd.Text == "")
            {
                MessageBox.Show("密码不能为空", "提示");
                return;
            }

            if (txtPwdCfm.Text == "")
            {
                MessageBox.Show("确认密码不能为空", "提示");
                return;
            }

            if (txtPwdCfm.Text != txtPwd.Text)
            {
                MessageBox.Show("两次输入的密码不相同", "提示");
                return;
            }
            #endregion

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                if (MessageBox.Show(string.Format("确定加密文件夹{0}?", folderBrowserDialog1.SelectedPath),
                    "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }

                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            pbDir.Value = 0;
                            lblProgressDir.Text = "0%";
                            pbFile.Value = 0;
                            lblProgressFile.Text = "0%";
                            pbDir.Visible = true;
                            lblProgressDir.Visible = true;
                            pbFile.Visible = false;
                            lblProgressFile.Visible = false;
                            lblShowPath.Text = "文件夹:" + folderBrowserDialog1.SelectedPath;
                            lblShowPath.Visible = true;
                            DisableBtns();
                        };
                        InvokeUtil.Invoke(this, invokeDelegate);
                        DateTime t1 = DateTime.Now;
                        DirectoryEncrypt.EncryptDirectory(folderBrowserDialog1.SelectedPath, txtPwd.Text, RefreshDirProgress, RefreshFileProgress);
                        DateTime t2 = DateTime.Now;
                        string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
                        if (MessageBox.Show("加密成功,耗时" + t + "", "提示") == DialogResult.OK)
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show("加密失败:" + ex.Message, "提示") == DialogResult.OK)
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                }));
                thread.Start();
            }
        }
        #endregion

        #region 文件夹解密
        private void btnDecryptDir_Click(object sender, EventArgs e)
        {
            #region 验证
            if (txtPwd.Text == "")
            {
                MessageBox.Show("密码不能为空", "提示");
                return;
            }
            #endregion

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                if (MessageBox.Show(string.Format("确定解密文件夹{0}?", folderBrowserDialog1.SelectedPath),
                    "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }

                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            pbDir.Value = 0;
                            lblProgressDir.Text = "0%";
                            pbFile.Value = 0;
                            lblProgressFile.Text = "0%";
                            pbDir.Visible = true;
                            lblProgressFile.Visible = true;
                            pbFile.Visible = false;
                            lblProgressFile.Visible = false;
                            lblShowPath.Text = "文件夹:" + folderBrowserDialog1.SelectedPath;
                            lblShowPath.Visible = true;
                            DisableBtns();
                        };
                        InvokeUtil.Invoke(this, invokeDelegate);
                        DateTime t1 = DateTime.Now;
                        DirectoryEncrypt.DecryptDirectory(folderBrowserDialog1.SelectedPath, txtPwd.Text, RefreshDirProgress, RefreshFileProgress);
                        DateTime t2 = DateTime.Now;
                        string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
                        if (MessageBox.Show("解密成功,耗时" + t + "", "提示") == DialogResult.OK)
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show("解密失败:" + ex.Message, "提示") == DialogResult.OK)
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            InvokeUtil.Invoke(this, invokeDelegate);
                        }
                    }
                }));
                thread.Start();
            }
        }
        #endregion

        #region 更新文件加密进度
        /// <summary>
        /// 更新文件加密进度
        /// </summary>
        public void RefreshFileProgress(int max, int value)
        {
            InvokeDelegate invokeDelegate = delegate()
            {
                if (max > 1)
                {
                    pbFile.Visible = true;
                    lblProgressFile.Visible = true;
                }
                else
                {
                    pbFile.Visible = false;
                    lblProgressFile.Visible = false;
                }
                pbFile.Maximum = max;
                pbFile.Value = value;
                lblProgressFile.Text = value * 100 / max + "%";
            };
            InvokeUtil.Invoke(this, invokeDelegate);
        }
        #endregion

        #region 更新文件夹加密进度
        /// <summary>
        /// 更新文件夹加密进度
        /// </summary>
        public void RefreshDirProgress(int max, int value)
        {
            InvokeDelegate invokeDelegate = delegate()
            {
                pbDir.Maximum = max;
                pbDir.Value = value;
                lblProgressDir.Text = value * 100 / max + "%";
            };
            InvokeUtil.Invoke(this, invokeDelegate);
        }
        #endregion文章地址https://www.yii666.com/blog/96403.html

        #region 显示密码
        private void cbxShowPwd_CheckedChanged(object sender, EventArgs e)
        {
            if (cbxShowPwd.Checked)
            {
                txtPwd.PasswordChar = default(char);
                txtPwdCfm.PasswordChar = default(char);
            }
            else
            {
                txtPwd.PasswordChar = '*';
                txtPwdCfm.PasswordChar = '*';
            }
        }
        #endregion

        #region 关闭窗体事件
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (progressPanel.Visible)
            {
                MessageBox.Show("正在处理文件,请等待…", "提示");
                e.Cancel = true;
            }
        }
        #endregion

        #region 控制按钮状态
        /// <summary>
        /// 禁用按钮
        /// </summary>
        public void DisableBtns()
        {
            progressPanel.Visible = true;
            btnEncrypt.Enabled = false;
            btnDecrypt.Enabled = false;
            btnEncryptDir.Enabled = false;
            btnDecryptDir.Enabled = false;
        }
        /// <summary>
        /// 启用按钮
        /// </summary>
        public void EnableBtns()
        {
            lblShowPath.Visible = false;
            progressPanel.Visible = false;
            btnEncrypt.Enabled = true;
            btnDecrypt.Enabled = true;
            btnEncryptDir.Enabled = true;
            btnDecryptDir.Enabled = true;
        }
        #endregion

    }
}
View Code

 

posted @ 2023-07-12 15:14  青丝·旅人  阅读(1381)  评论(0编辑  收藏  举报