Reputation: 67
I am making a small tool to get the hashes of a file or directory to view checksums. Right now I have it displaying the hashes of a single file but when I try and get an entire directory I get the error System.UnauthorizedAccessException: 'Access to the path 'D:\dev\hashcheck' is denied.'
.
Here is a simplified version of the code, simplified only because it's very repetitive.
byte[] fileByte = File.ReadAllBytes(path); //This is where the error is
MD5 md5Hash = MD5.Create();
Console.WriteLine("The MD5 Hash of the file is; " +
BitConverter.ToString(md5Hash.ComputeHash(fileByte))
.Replace("-", string.Empty)
.ToLower());
I have tried adding <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
to the application manifest.
Upvotes: 0
Views: 5180
Reputation: 52290
According to the documentation for ReadAllBytes, the first parameter is:
path. String The file to open for reading.
So you must supply the path of a file, not the path of anything else. A directory of course is not a file, so it's not going to work.
I am not sure what you mean by "hash of a directory" but it seems to me you may have to open the individual files (in a deterministic order), concatenate their bytes, then run the hash algorithm over the whole thing, i.e. generate a virtual byte stream comprising the entire fileset.
var virtualByteStream = Directory
.GetFiles(path)
.OrderBy( p => p )
.SelectMany
(
p => p.ReadAllbytes()
);
var hash = md5Hash.ComputeHash(virtualByteStream.ToArray());
Note that this approach does not include file metadata (e.g. DateModified), so if that is important to you then you'd need to include it, and any other metadata, in the hash input.
(If your files are large, you may want to find a way to avoid the ToArray()
call and use ComputeHash(Stream)
instead. But that is beyond the scope of this answer.)
Upvotes: 2
Reputation: 10930
You need to get all files in the Directory before you can read the content, like this:
using System.IO;
foreach (string file in Directory.GetFiles(path))
{
byte[] fileByte = File.ReadAllBytes(file);
MD5 md5Hash = MD5.Create();
Console.WriteLine("The MD5 Hash of the file is; " +
BitConverter.ToString(md5Hash.ComputeHash(fileByte))
.Replace("-", string.Empty)
.ToLower());
}
Upvotes: 1