Question

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?

Était-ce utile?

La solution

My guess is that you are opening the file twice in your second piece of code:

using (var sw = File.AppendText(filePath + fileName))
{
    sw.Write(ctx.GetMD5HashFromFile(filePath, fileName));
}

ctx.GetMD5HashFromFile probably opens the file to create the hash; but you already opened it to append data. So create the hash before the File.AppendText using block.

Autres conseils

You are not closing the file on creation, try:

if (!File.Exists(filePath))
{
      using (var sw = File.CreateText(filePath))
      {
            sw.Write("Stuff to write");
      }
 }
 FileStream file = File.OpenRead(filePath);
 string hashString = ctx.GetMD5HashFromFile(file);
 file.Close();

 File.WriteAllText(filePath, hashString);

only open the file for reading when getting the hash:

C# calculate MD5 for opened file?

I advise to use Sha1Sum instead of MD5 which is very old and unsafe

This function return the value in format "C61211674FD03175FEC87A9C01F39F72376CE104"

    public static string MakeSha(string Mystr)
    {
        SHA1CryptoServiceProvider Crpyt = new SHA1CryptoServiceProvider();
        byte[] buf = ASCIIEncoding.ASCII.GetBytes(Mystr);
        return BitConverter.ToString(Crpyt.ComputeHash(buf)).Replace("-", "").ToUpper();
    }

PS: Don't forget to add in using statement the following using System.Security.Cryptography;

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top