I am trying to append a MD5 hash (based on the length of a file) of a file after the file is closed. I am doing that like this:
string filePath = "myPath";
string fileName = "myFileName";
File.Delete(filePath + fileName);
if (!File.Exists(filePath + fileName))
{
using (var sw = File.CreateText(filePath + fileName))
{
sw.Write("Stuff to write");
}
}
using (var sw = File.AppendText(filePath + fileName))
{
sw.Write(ctx.GetMD5HashFromFile(filePath, fileName));
}
Unfortunately this does not work since the file is not closed properly in between the two using statements. I get the following error:
Unhandled Exception: System.IO.IOException: The process cannot access the file '
[filePath + fileName] because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
How can I compute the MD5 hash properly and append the text without getting an exception?