C# MD5 hasher example

后端 未结 6 1215
慢半拍i
慢半拍i 2020-12-09 19:16

Edit: I\'ve retitled this to an example as the code works as expected.

I am trying to copy a file, get a MD5 hash, then delete the copy. I am doing

6条回答
  •  萌比男神i
    2020-12-09 19:42

    I took your code put it in a console app and ran it with no errors, got the hash and the test file is deleted at the end of execution? I just used the .pdb from my test app as the file.

    What version of .NET are you running?

    I am putting the code that I have that works here, and if you put this in a console app in VS2008 .NET 3.5 sp1 it runs with no errors (at least for me).

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography;
    using System.IO;
    
    namespace lockTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                string hash = GetHash("lockTest.pdb");
    
                Console.WriteLine("Hash: {0}", hash);
    
                Console.ReadKey();
            }
    
            public static string GetHash(string pathSrc)
            {
                string pathDest = "copy_" + pathSrc;
    
                File.Copy(pathSrc, pathDest, true);
    
                String md5Result;
                StringBuilder sb = new StringBuilder();
                MD5 md5Hasher = MD5.Create();
    
                using (FileStream fs = File.OpenRead(pathDest))
                {
                    foreach (Byte b in md5Hasher.ComputeHash(fs))
                        sb.Append(b.ToString("x2").ToLower());
                }
    
                md5Result = sb.ToString();
    
                File.Delete(pathDest);
    
                return md5Result;
            }
        }
    }
    

提交回复
热议问题