How to test if a file is fully copied in .NET

后端 未结 9 1345
小鲜肉
小鲜肉 2021-01-17 12:27

I am monitoring a folder for new files and need to process them. The problem is that occasionally file opening fails, because system has not finished copying it.

Wha

9条回答
  •  死守一世寂寞
    2021-01-17 12:28

    Are the files big?

    Maybe you could try to calculate a the md5 checksum on the file?

    If you put the md5 hash in the filename you could retrieve it and try to recalculate the checksum on the file. When the md5 is a match you could assume that the file is finished.

    byte[] md5Hash = null;
    MD5 md5 = new MD5CryptoServiceProvider();
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
       md5Hash = md5.ComputeHash(fs);
    
    StringBuilder hex = new StringBuilder();
    foreach (byte b in md5Hash)
        hex.Append(b.ToString("x2"));
    

提交回复
热议问题