Calculate the MD5 of a file while reading from a text file

C Sharp - C# (programming language)
Post Reply
dzcadii
Posts: 94
Joined: Sun Mar 01, 2015 4:36 am

Calculate the MD5 of a file while reading from a text file

Post by dzcadii » Sun Mar 01, 2015 10:52 pm

Code: Select all

//Use these namespaces
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;


            
//Counter for found files
int i = 0;
//Loop through the dir and read the files
using (var writer = new StreamWriter(logfile))
    {
          //Runs through all directories and subdirectories
         foreach (string file in Directory.GetFiles(targetdir, "*.*", SearchOption.AllDirectories))
         //Run ONLY through this directory
        //foreach (string file in Directory.GetFiles(targetdir))
          {
               //Get MD5 of file
               string m5 = GetMD5(file);
               //File size
               FileInfo fInfo = new FileInfo(file);
               //Writing to a log file
               writer.Write("<|>" + Path.GetFileName(file) + "::<>::" + m5 + "<|>::::" + file + "::<>::" + fInfo.Length + "\r\n");
               //Counter
               i++;
               //Write to console for debug
               Console.WriteLine(Path.GetFileName(file) + "::<>::" + m5 + "::::<|>" + file + "<|>" + fInfo.Length + "\r\n");
          }



private static string GetMD5(string target)
{
  System.IO.FileStream fs = new FileStream(target, FileMode.Open, FileAccess.Read);
  System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
  byte[] bytes = md5.ComputeHash(fs);
  StringBuilder sBuilder = new StringBuilder();
  for (int i = 0; i < bytes.Length; i++)
       {
           sBuilder.Append(bytes[i].ToString("x2"));
       }
   fs.Close();
   return sBuilder.ToString();
}

Post Reply