问题
Right now by code looks like the following:
private void DatabaseIntegrityCheck()
{
try
{
string m_checksum;
using (FileStream stream = File.OpenRead(@"C:\~\db.mdf"))
{
SHA256Managed sha = new SHA256Managed();
byte[] checksum = sha.ComputeHash(stream);
m_checksum = BitConverter.ToString(checksum).Replace("-", String.Empty);
}
Console.WriteLine(m_checksum);
}
catch (Exception ex)
{
Console.WriteLine("unable to retrieve checksum");
}
}
When I set a breakpoint in my code to see what the exception is, I get a IOException that says:
The process cannot access the file 'db.mdf' because it is being used by another process.
The way I am running the checksum is there's a button in my window and when I click it, the method above is being called to perform the action. I want to check and see if it works first, so I just Console.WriteLine the checksum hash but the exception above is being thrown.
What can I do to fix this?
回答1:
Try the following code:
try
{
string mChecksum;
using (FileStream stream = File.OpenRead(@"E:\draft.pdf"))
{
var sha = new SHA256Managed();
var cs = new CryptoStream(stream, sha, CryptoStreamMode.Read);
cs.FlushFinalBlock();
byte[] hash = sha.Hash;
mChecksum = BitConverter.ToString(hash).Replace("-", String.Empty);
}
Console.WriteLine(mChecksum);
}
catch (Exception ex)
{
Console.WriteLine("unable to retrieve checksum");
}
See details about CryptoStream
来源:https://stackoverflow.com/questions/25040912/db-mdf-is-being-used-by-another-process