這是我的類從每個目錄返回最新的文件,問題是,儘管我把我的代碼放在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);
}
}
這是什麼意思?它發生在哪一行? 您是否遇到異常並且調試程序警告您,或者異常是否會使應用程序崩潰? –
此外,我認爲你的代碼可能存在問題:你沒有防範可能導致無限循環的nfts聯接文件夾,另外,如果你使用臨時文件,當你使用字典條目時這可能會消失。 –
發生異常var files = from Directory.GetFiles(directory,「*。*」)中的文件 選擇新的FileInfo(file); – user2214609