C#计算MD5为打开的文件? [英] C# calculate MD5 for opened file?

查看:124
本文介绍了C#计算MD5为打开的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算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.

这篇关于C#计算MD5为打开的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆