开发者

Generate checksum without opening the file

开发者 https://www.devze.com 2023-02-02 05:28 出处:网络
开发者_高级运维Is there a way to calculate the checksum of a file that is readonly? The only examples I have seen uses an algorithm like this

开发者_高级运维Is there a way to calculate the checksum of a file that is readonly?

The only examples I have seen uses an algorithm like this

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

    StringBuilder sb = new StringBuilder();
    foreach (byte t in retVal)
    {
        sb.Append(retVal[1].ToString("x2"));
    }
    return sb.ToString();
}


You can open a file even if it's readonly.
It is not possible to generate a checksum without opening the file, since you can't read a file without opening it.

You should pass FileAccess.Read to open it as read-only.

Also, you should generate checksums using SHA512, not MD5.


According to the documentation, the FileStream constructor you are using opens the file for read/write. Use an overload that specifies FileAccess.Read.

The constructor is given read/write access to the file, and it is opened sharing Read access


You cannot generate a checksum without reading the entire file.

Generally, readonly files can be opened. There might be file or folder permissions that prevent a given user from opening the file.


Well, no. You have to read a file to do anything with what's in it. But you're opening with Generic access when you probably want FileStream(_filePath,FileAccess.Read,true,4096,true); to open it read-only. StreamReader will do this automatically.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号