取得檔案MD5碼及版本號

摘要:取得檔案MD5碼

常逛論壇的人都會發現,有些人上傳檔案時都會附上MD5碼,用意是為了確保使用者下載的檔案與來源檔案一致,

今天User提出需要驗證POS機與server端程式需檢查MD5碼及版本號的需求,所以就上網查了一下作法,以下是我的測試程式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;
using System.Diagnostics;


namespace MD5Checksum
{
    class Program
    {
        [STAThreadAttribute]
        public static void Main(String[] args)
        {            
            try
            {
                string path = ConfigurationManager.AppSettings["CheckPath"];
                GetVersion(path);
                PrintByteArray(GetMD5(path));
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine("Error: The directory specified could not be found.");
            }
            catch (IOException)
            {
                Console.WriteLine("Error: A file in the directory could not be accessed.");
            }
        }

        public static byte[] GetMD5(string filename)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(filename))
                {
                    return md5.ComputeHash(stream);
                }
            }
        }

        public static void GetVersion(string filename)
        {
            Console.Write(FileVersionInfo.GetVersionInfo(filename).FileVersion.ToString());
            Console.WriteLine();
        }

        // Print the byte array in a readable format.
        public static void PrintByteArray(byte[] array)
        {
            int i;
            for (i = 0; i < array.Length; i++)
            {
                Console.Write(String.Format("{0:X2}", array[i]));
                
            }
            Console.WriteLine();
        }
    }
}