tags:

views:

94

answers:

2

Hello,

how I can calculate MD5 hash for a file that is open or used by a process?

the files can be txt or and exe

my current code return error for an exe because it is running

here is my current code

public static string GetMd5HashFromFile(string fileName)
        {
            FileStream file = new FileStream(fileName, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

cheers

+4  A: 

Try opening the file as read-only:

FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);

or:

FileStream file = File.OpenRead(fileName);

That will work depending on the sharing mode of the other file handles. If the file is only locked because it is a running EXE, I think this will be enough.

Quartermeister
Thanks allot, worked perfectly :-)
Data-Base
+3  A: 

If you update your FileStream constructor call to this;

FileStream file = File.Open(fileName,
                            FileMode.Open,
                            FileAccess.Read,
                            FileShare.ReadWrite);

That should allow you to open a file which is being used by another process.

C.McAtackney