C# calculate MD5 for opened file?
Asked Answered
R

2

10

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.

Reedbuck answered 4/8, 2010 at 12:57 Comment(0)
D
10

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.

Dosi answered 4/8, 2010 at 13:6 Comment(0)
P
7

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.

Pule answered 4/8, 2010 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.