Edit: I've retitled this to an example as the code works as expected.
I am trying to copy a file, get a MD5 hash, then delete the copy. I am doing this to avoid process locks on the original file, which another app writes to. However, I am getting a lock on the file I've copied.
File.Copy(pathSrc, pathDest, true);
String md5Result;
StringBuilder sb = new StringBuilder();
MD5 md5Hasher = MD5.Create();
using (FileStream fs = File.OpenRead(pathDest))
{
foreach(Byte b in md5Hasher.ComputeHash(fs))
sb.Append(b.ToString("x2").ToLower());
}
md5Result = sb.ToString();
File.Delete(pathDest);
I am then getting a 'process cannot access the file' exception on File.Delete()
'.
I would expect that with the using
statement, the filestream would be closed nicely. I have also tried declaring the filestream separately, removing using
, and putting fs.Close()
and fs.Dispose()
after the read.
After this, I commented out the actually md5 computation, and the code excutes, with the file being deleted, so it looks like it's something to do with ComputeHash(fs)
.