Form1.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Windows.Forms;
  10. namespace FileToMD5
  11. {
  12. public partial class Form_MD5 : Form
  13. {
  14. public Form_MD5()
  15. {
  16. InitializeComponent();
  17. }
  18. private void btn_md5_Click(object sender, EventArgs e)
  19. {
  20. OpenFileDialog ofd = new OpenFileDialog();
  21. ofd.InitialDirectory = "D:\\";
  22. try
  23. {
  24. if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  25. {
  26. txtFilePath.Text = ofd.FileName;
  27. //创建一个文件对象
  28. FileInfo EzoneFile = new FileInfo(txtFilePath.Text);
  29. //打开文件流
  30. FileStream EzoneStream = EzoneFile.OpenRead();
  31. //EzoneStream.Position = 0;
  32. long size = EzoneStream.Length;
  33. byte[] array = new byte[size];//文件
  34. EzoneStream.Read(array, 0, array.Length);
  35. string md5 = GetMD5HashFromFile(array);
  36. txtMd5.Text = md5;
  37. EzoneStream.Close();
  38. EzoneStream = null;
  39. EzoneFile = null;
  40. }
  41. }
  42. catch (Exception ex)
  43. {
  44. MessageBox.Show(ex.Message);
  45. }
  46. }
  47. public static string GetMD5HashFromFile(byte[] filedatas)
  48. {
  49. try
  50. {
  51. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  52. byte[] retVal = md5.ComputeHash(filedatas);
  53. StringBuilder sb = new StringBuilder();
  54. for (int i = 0; i < retVal.Length; i++)
  55. {
  56. sb.Append(retVal[i].ToString("x2"));
  57. }
  58. return sb.ToString();
  59. }
  60. catch (Exception ex)
  61. {
  62. //errorinfo = ex.Message.ToString();
  63. return "";
  64. }
  65. }
  66. }
  67. }