C#计算MD5为打开的文件?文件

2023-09-03 12:23:30 作者:你若不离我绝不弃

我如何计算MD5哈希值的文件,该文件是打开或使用的过程?

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

该文件可以TXT或和e​​xe

the files can be txt or and exe

由于它运行我目前的code返回错误对于EXE

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

下面是我现在的code

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();
}

干杯。

推荐答案

尝试打开该文件为只读的:

Try opening the file as read-only:

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

FileStream file = File.OpenRead(fileName);

这将取决于其它文件句柄的共享模式下工作。如果该文件只锁定,因为它是一个正在运行的EXE,我认为这将是足够的。

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.

 
精彩推荐
图片推荐