まず第一に、コードを見て長すぎると言ってはいけません。
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;
}
}