【问题标题】:being used by another process (after a file.openread(), but then .Close())被另一个进程使用(在 file.openread() 之后,然后是 .Close())
【发布时间】:2015-09-23 09:02:15
【问题描述】:

首先——不要看代码就说太长 它只是看起来那样。

我正在编写一个程序,它将搜索我的计算机并根据其 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;
  }
}

【问题讨论】:

  • 您已经让资源管理器告诉您哪个进程锁定了文件?那很臭,禁用任何实用程序,然后重试。 Win7 有一个错误,偶尔(注意)会阻止删除最近关闭的文件。你必须睡一会儿再试一次。

标签: c# fileinfo


【解决方案1】:

我不知道这是否是关键,但是您在 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多