db.mdf is being used by another process

≡放荡痞女 提交于 2019-12-25 01:54:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!