C# calculate MD5 for opened file?

梦想与她 提交于 2019-12-20 19:57:28

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3405705/c-sharp-calculate-md5-for-opened-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!