批量生成文件的md5校驗碼,帶源碼

有的時候, 我們爲了保證發佈在網上的文件爲原始的正確的文件,沒被修改過,這時需要把文件生成校驗碼,用於下載後文件的校驗.以下程序可以指定文件路徑及輸出文件的路徑,對滿足指定擴展名的文件,進md5碼計算,輸出到.md5文件及文本文件,並顯示在界面當中.

也可以點擊這裏下載源代碼: 下載

點擊這裏下載程序: 下載

程序分爲兩個文件來組織,分別爲CheckEntity.cs及frmMain.cs.CheckEntity.cs中包含實體類,md5生成輸出類.frmMain.cs主要爲操作生成及設置的界面.

源代碼分別如下:

CheckEntity.cs文件:



using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Windows.Forms;

namespace Md5Check
{
    [Serializable]
    public class CheckEntity
    {
        public string FileName { get; set; }
        public string Md5Code { get; set; }
        public DateTime CreateDate { get; set; }
        public DateTime ModifyDate { get; set; }
        public string FileFullName { get; set; }
    }

    [Serializable]
    public class CheckActivety
    {
        public List<CheckEntity> Actives { get; set; }
        public DateTime CheckDate { get; set; }
        public int FileCnt { get; set; }
    }

    public static class Helper
    {
        public static void BinSerialize(object obj, string fileName)
        {
            using (System.IO.Stream strm = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.None))
            {
                System.Runtime.Serialization.IFormatter fmt = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                fmt.Serialize(strm, obj);
                strm.Flush();
            }
        }

        public static object BinDeserialize(string fileName)
        {
            object obj = null;
            using (System.IO.Stream strm = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
            {
                System.Runtime.Serialization.IFormatter fmt = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                obj = fmt.Deserialize(strm);
            }
            return obj;
        }

        public static string GetMD5Code(string fileName)
        {
            string hashCode = "";
            if (File.Exists(fileName))
            {
                StreamReader srd = new StreamReader(fileName);
                MD5 md = MD5.Create();
                byte[] bts = Encoding.UTF32.GetBytes(srd.ReadToEnd());
                byte[] code = md.ComputeHash(bts);
                for (int i = 0; i < code.Length; i++)
                    hashCode += code[i].ToString("x");
            }
            return hashCode;
        }
    }

    public class Check
    {
        public string ResultFileName { get; set; }
        public string RootPath { get; set; }

        private string _ExtendNames = ".cs,.asmx,.aspx,.resx,.bat";
        public string ExtendNames
        {
            get { return _ExtendNames; }
            set { _ExtendNames = value; }
        }

        #region Paths
        private string[] _CheckPaths;
        public string[] CheckPaths
        {
            get { return _CheckPaths; }
            set { _CheckPaths = value; }
        }
        #endregion

        private DateTime BeginTime { get; set; }
        private DateTime EndTime { get; set; }
        public bool ShowFoldSelector { get; set; }
        public bool ShowSavePathSelector { get; set; }
        public bool ExpertToTextFile { get; set; }
        private List<CheckEntity> _Actives;
        public List<CheckEntity> Actives
        {
            get
            {
                if (Activity != null)
                    _Actives = Activity.Actives;
                return _Actives;
            }
        }

        public CheckActivety Activity { get; set; }

        public Check(bool _ShowFoldSelector, bool _ShowSavePathSelector, bool _ExpertToTextFile)
        {
            ResultFileName = Application.StartupPath+"\\Check" + DateTime.Now.ToShortDateString() + ".md5";
            ShowFoldSelector = _ShowFoldSelector;
            ShowSavePathSelector = _ShowSavePathSelector;
            ExpertToTextFile = _ExpertToTextFile;
            Activity = new CheckActivety();
        }

        public void Start()
        {
            if (ShowFoldSelector)
            {
                //這裏可以不必要這樣做,以下主要是爲了手工指定不連續文件夾方便
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    RootPath = fbd.SelectedPath;
                    CheckPaths = Directory.GetDirectories(RootPath);
                    string[] NewCheckPaths = new string[CheckPaths.Length + 1];
                    NewCheckPaths[0] = fbd.SelectedPath;
                    Array.Copy(CheckPaths, 0, NewCheckPaths, 1, CheckPaths.Length);
                    CheckPaths = NewCheckPaths;
                }
            }

            if (ShowSavePathSelector)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "MD5文件(*.md5)|*.md5";
                if (sfd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(sfd.FileName))
                    ResultFileName = sfd.FileName;
            }

            /*
            ThreadStart startDelegate = new ThreadStart(StartCheck);
            Thread thd = new Thread(startDelegate);
            thd.Start();
            */

            StartCheck();
        }

        private void StartCheck()
        {
            try
            {
                BeginTime = DateTime.Now;
                Activity.CheckDate = DateTime.Now;
                Activity.FileCnt = 0;
                Activity.Actives = new List<CheckEntity>();

                for (int i = 0; i < CheckPaths.Length; i++)
                {
                    GetHashValues(Activity, Activity.Actives, CheckPaths[i]);
                }

                //Serialize the result and save to file
                Helper.BinSerialize(Activity, ResultFileName);

                //Save Result to text file
                if (ExpertToTextFile)
                {
                    StringBuilder sbResult = new StringBuilder();
                    int j = 1;
                    foreach (CheckEntity entity in Activity.Actives)
                    {
                        sbResult.AppendLine(string.Format("{0,4}. Code:{1,35} <- {2,50} : [{3}]", j, entity.Md5Code.ToUpper(), entity.FileName, entity.FileFullName));
                        j++;
                    }

                    try
                    {
                        using (StreamWriter sw = new StreamWriter(ResultFileName + ".txt"))
                        {
                            sw.Write(sbResult.ToString());
                            sw.Flush();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Save to text file failed! Error Infomation is :" + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                EndTime = DateTime.Now;

                MessageBox.Show(string.Format("Computed! Time ellapse: {0} ms  Files: {1} ", (EndTime - BeginTime).TotalMilliseconds, Activity.FileCnt), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error has happend when Compute hash values :" + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void GetHashValues(CheckActivety chk, List<CheckEntity> lst, string dirPath)
        {
            if (Directory.Exists(dirPath))
            {
                DirectoryInfo dir = new DirectoryInfo(dirPath);
                CheckEntity file = null;

                foreach (FileInfo f in dir.GetFiles())
                    if (ExtendNames.Contains(f.Extension))
                    {
                        file = new CheckEntity();
                        file.CreateDate = f.CreationTime;
                        file.ModifyDate = f.LastWriteTime;
                        file.FileFullName = f.FullName;
                        file.FileName = f.Name;
                        file.Md5Code = Helper.GetMD5Code(f.FullName);

                        chk.Actives.Add(file);
                        chk.FileCnt++;
                    }

                DirectoryInfo[] dirs = dir.GetDirectories();
                if (dirs.Length > 0)
                    foreach (DirectoryInfo dirInfo in dirs)
                        if (!dirInfo.Name.Equals(RootPath, StringComparison.InvariantCultureIgnoreCase)) //根目錄不再遞歸
                            GetHashValues(chk, lst, dirInfo.FullName);
            }
        }
    }
}




frmMain.cs文件:
using System;
using System.Windows.Forms;

namespace Md5Check
{
    public class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Check chk = new Check(true, true, true);
            chk.ExtendNames = this.txtExtension.Text.Trim();
            chk.Start();
            this.dgvResult.DataSource = chk.Actives;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.DataGridView dgvResult;
        private System.Windows.Forms.Button btnExit;
        private System.Windows.Forms.TextBox txtExtension;
        private System.Windows.Forms.Label label1;
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        private void InitializeComponent()
        {
            this.btnStart = new System.Windows.Forms.Button();
            this.dgvResult = new System.Windows.Forms.DataGridView();
            this.btnExit = new System.Windows.Forms.Button();
            this.txtExtension = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.dgvResult)).BeginInit();
            this.SuspendLayout();
            // 
            // btnStart
            // 
            this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnStart.Location = new System.Drawing.Point(410, 433);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 0;
            this.btnStart.Text = "Start";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // dgvResult
            // 
            this.dgvResult.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dgvResult.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvResult.Location = new System.Drawing.Point(12, 12);
            this.dgvResult.Name = "dgvResult";
            this.dgvResult.RowTemplate.Height = 23;
            this.dgvResult.Size = new System.Drawing.Size(554, 412);
            this.dgvResult.TabIndex = 1;
            // 
            // btnExit
            // 
            this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnExit.Location = new System.Drawing.Point(491, 433);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(75, 23);
            this.btnExit.TabIndex = 0;
            this.btnExit.Text = "Exit";
            this.btnExit.UseVisualStyleBackColor = true;
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            // 
            // txtExtension
            // 
            this.txtExtension.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtExtension.Location = new System.Drawing.Point(114, 435);
            this.txtExtension.Name = "txtExtension";
            this.txtExtension.Size = new System.Drawing.Size(290, 21);
            this.txtExtension.TabIndex = 2;
            this.txtExtension.Text = ".cs,.asmx,.aspx,.resx,.bat,.dll,.exe";
            // 
            // label1
            // 
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(10, 438);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(101, 12);
            this.label1.TabIndex = 3;
            this.label1.Text = "File Extensions:";
            // 
            // frmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(578, 465);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtExtension);
            this.Controls.Add(this.dgvResult);
            this.Controls.Add(this.btnExit);
            this.Controls.Add(this.btnStart);
            this.Name = "frmMain";
            this.Text = "Computer Md5 Code Batch";
            ((System.ComponentModel.ISupportInitialize)(this.dgvResult)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章