常逛论坛的人都会发现,有些人上传档案时都会附上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();
}
}
}