我有以下 C# 代码用于计算某个用户指定目录中每个文件的哈希值。关键是它可以正常工作,直到遇到无法访问的文件。当它发现这样的东西时,它只是抛出一条错误消息并退出程序。我想要它做的是,抛出一条带有无法访问的文件名的错误消息,写下访问该文件时出错,然后继续使用目录中的其他文件执行程序。如果有人可以帮助我编辑我的代码并实现这些目标,我会很高兴。
private void SHA256Directory(string directory)
{
try
{
SHA256 DirectorySHA256 = SHA256Managed.Create();
byte[] hashValue;
DirectoryInfo dir = new DirectoryInfo(directory);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo fInfo in files)
{
FileStream fStream = fInfo.Open(FileMode.Open);
fStream.Position = 0;
hashValue = DirectorySHA256.ComputeHash(fStream);
Console.WriteLine(fInfo.Name);
Miscellaneous.ByteArrayToHex(hashValue);
Miscellaneous.ByteArrayToBase64(hashValue);
Console.WriteLine();
fStream.Close();
}
return;
}
catch(DirectoryNotFoundException)
{
Console.WriteLine("Error: The directory specified could not be found.");
}
catch(IOException)
{
Console.WriteLine("Error: A file in the directory could not be accessed.");
}
catch(ArgumentNullException)
{
Console.WriteLine("Error: The argument cannot be null or empty.");
}
}