I need to compute a SHA1 on a file that is changing often. I can copy, paste, open the archive in Windows Explorer, but I get an UnauthorizedAccessException on the using instruction.. The exception suggests I have a read only file, which doesn’t seem to be true in the properties of the file.
The archive sits on a shared drive at a location that I have full access on.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace TheTest
{
public class MakeSha1
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(@"###.xml.gz", FileMode.Open))
{
using (SHA1Managed sha1 = new SHA1Managed())
{
byte[] hash = sha1.ComputeHash(fs);
StringBuilder formatted = new StringBuilder(hash.Length);
foreach (byte b in hash)
{
formatted.AppendFormat("{0:X2}", b);
}
Console.WriteLine(formatted.ToString());
}
Console.ReadKey();
}
}
}
}
The constructor you are using for
FileStreamdoes not explicitly specify file sharing, and so no file sharing is permitted by default. If the file is being modified frequently, then you might be better off using a different form of the constructor:Note that if another process modifies the file while you are processing, then your SHA1 will not be accurate.