Catch访问路径被拒绝异常
本文关键字:拒绝 异常 路径 访问 Catch | 更新日期: 2023-09-27 18:28:29
这是我的类,它从每个目录返回最新的文件,问题是尽管我把代码放在Try-Catch块中,但我仍然收到路径被拒绝的错误
public class NewestFiles
{
//public event EventHandler newFileEventHandler;
// Dictionary:
// Key = The directory name.
// Value = The most recently modified file for that directory.
private Dictionary<string, string> GetNewestFiles(string directory, Dictionary<string, string> dictionary)
{
if (dictionary == null)
dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
var files = from file in Directory.GetFiles(directory, "*.*")
select new FileInfo(file);
var latestFile = files.OrderByDescending(file => { return file.LastWriteTimeUtc; }).FirstOrDefault();
if (latestFile != null)
dictionary[latestFile.DirectoryName] = latestFile.FullName;
}
catch(Exception)
{ }
foreach (var subDirectory in Directory.GetDirectories(directory))
{
try
{
GetNewestFiles(subDirectory, dictionary);
}
catch { }
}
return dictionary;
}
public Dictionary<string, string> GetNewestFiles(string directory)
{
return GetNewestFiles(directory, null);
}
}
尽管我把我的代码放在Try-Catch块中,但我仍然得到了路径被拒绝的错误
Try-catch不防止错误,它们只捕捉异常,以便在发生不好的事情时以良好的方式处理
现在你的错误
拒绝访问路径异常
由于错误本身表明您没有访问要读取的文件/目录的权限。或者,如果您自己编写了该文件(从代码中可以看出),则可能是您没有正确关闭编写器。
通常当您获得access to the path is denied exception
时,意味着其他程序正在保存该文件。处理文件、流或数据库时,应使用using
语句,以防止不关闭流。
然而,有一些方法可以强制获取文件,或者至少找出锁定它的进程。在这里,您可以看到如何开始使用它