0

首先 - 不要看代码并说它太长了,它只是看起来那样。

我正在编写一个程序,它将搜索我的计算机并根据它们的 MD5 值删除文件(为了加快速度,我不想搜索所有文件,只是那些具有特定文件名的文件)。

我将 FileInfo 发送到名为 ConditionallyDeleteNotWantedFile 的方法,然后它获取该文件的名称并尝试在字典中找到它 - 检索该文件的 MD5 并计算当前 FileInfo MD5 以查看它们是否相同。如果是 - 删除文件。

问题?当我尝试删除时抛出异常......即使没有其他进程使用它。当我尝试使用 Windows 资源管理器删除文件时,它显示 vshost(意思是:VS ...)

我错过了什么?

public static bool ConditionallyDeleteNotWantedFile(FileInfo fi)
{
  string dictMD5;
  if (NotWanted.TryGetValue(fi.Name, out dictMD5))
  {
    string temp = ComputeMD5Hash(fi.FullName);
    // temp will only be null if we couldn't open the file for 
    // read in the md5 calc operation. probably file is in use.
    if (temp == null) 
      return false; 
    if (temp == dictMD5)
    {
      try
      {
        fi.Delete();
      }
      catch { fi.Delete();   // this exception is raised with 
                             // "being used by another process"
      }
      return true;
    }
  }
  return false;
}

public static string ComputeMD5Hash(string fileName)
{
  return ComputeHash(fileName, new MD5CryptoServiceProvider());
}

public static string ComputeHash(string fileName, HashAlgorithm
    hashAlgorithm)
{
  try
  {
    FileStream stmcheck = File.OpenRead(fileName);
    try
    {
      stmcheck = File.OpenRead(fileName);
      byte[] hash = hashAlgorithm.ComputeHash(stmcheck);
      string computed = BitConverter.ToString(hash).Replace("-", "");
      stmcheck.Close();
      return computed;
    }
    finally
    {
      stmcheck.Close();
    }
  }
  catch
  {
    return null;
  }
}
4

1 回答 1

4

我不知道这是否是关键,但是您在 ComputeHash 中打开了两次流,并且有一条路径不会关闭它。我可以建议这个:

public static string ComputeHash(string fileName, HashAlgorithm hashAlgorithm)
{
    string hashFixed = null;
    try
    {
        using (FileStream stmcheck = File.OpenRead(fileName))
        {
            try
            {
                byte[] hash = hashAlgorithm.ComputeHash(stmcheck);
                hashFixed = BitConverter.ToString(hash).Replace("-", "");
            }
            catch
            {
                //logging as needed
            }
            finally
            {
                stmcheck.Close();
            }
        }
    }
    catch
    {
        //logging as needed
    }
    return hashFixed;
}
于 2011-03-04T22:34:45.167 回答