是的,我创建了一个应用程序,它将列出文件夹和子文件夹中的所有文件,但是当我尝试在c:windows中列出文件列表时,我收到了此错误“UnauthorizedAccessException”。我正在使用foreach循环,以解决错误,我已经捕获错误但它将结束应用程序。如何跳过此错误并转到另一个文件。这是我所做的代码。
try
{
//linecount2 = Directory.GetFiles(path2).Count();
//textBox1.Text = linecount2.ToString();
foreach (string file in Directory.GetFiles(path2, "*.*", SearchOption.AllDirectories))
{
currentpath = file;
Directory.GetAccessControl(file);
DateTime creationdate = File.GetCreationTime(file);
DateTime modidate = File.GetLastWriteTime(file);
textBox1.Text = "[" + file + "]" + "[" + creationdate + "]" + "[" + creationdate + "]";
ReportLog(savefile);
}
}
catch (DirectoryNotFoundException e)
{
textBox1.Text = "[" + readpath + "]" + "[No path available]" + "[]";
ReportLog(savefile);
}
catch (UnauthorizedAccessException e)
{
textBox1.Text = "[" + currentpath + "]" + "[Unauthorized Access]" + "[]";
ReportLog(savefile);
}
如果可能的话我想要包含隐藏的文件。这真的有帮助。
答案 0 :(得分:0)
您的代码存在的问题是任何错误都会导致代码跳出循环。相反,将错误捕获到for循环中:
foreach (string file in Directory.GetFiles(path2, "*.*", SearchOption.AllDirectories))
{
try
{
currentpath = file;
Directory.GetAccessControl(file);
DateTime creationdate = File.GetCreationTime(file);
DateTime modidate = File.GetLastWriteTime(file);
textBox1.Text = "[" + file + "]" + "[" + creationdate + "]" + "[" + creationdate + "]";
ReportLog(savefile);
}
catch (DirectoryNotFoundException e)
{
textBox1.Text = "[" + readpath + "]" + "[No path available]" + "[]";
ReportLog(savefile);
}
catch (UnauthorizedAccessException e)
{
textBox1.Text = "[" + currentpath + "]" + "[Unauthorized Access]" + "[]";
ReportLog(savefile);
}
}
但是您的代码还存在一些其他问题,并且循环中的代码似乎没有做任何有用的事情。
答案 1 :(得分:0)
你必须使用像这样的递归函数:
public static List<string> GetRecords(string path)
{
List<string> records;
try
{
records = Directory.GetFiles(path)
.Select(
o => string.Format("[{0}][{1}][{2}]", o, File.GetCreationTime(o), File.GetLastWriteTime(o)))
.ToList();
foreach (var directory in Directory.GetDirectories(path))
{
records.AddRange(GetRecords(directory));
}
return records;
}
catch (UnauthorizedAccessException)
{
return new List<string> {string.Format("[{0}][Unauthorized Access][]", path)};
}
catch (DirectoryNotFoundException)
{
return new List<string> { string.Format("[{0}][No path available][]", path) };
}
}