I have a program written in C# which lists all files in all directories except that ones where you need admin rights. It has no errors but always gives me an access denied exception for a directory that I already ignore. The access denied exception is for "C:$Recycle.Bin\S-1-5-18". Actually, I ignrore this directory AND run the program with admin rights but the exception is still here.Can anyone help me? Thanks
static void List()
{
List<string> files = new List<string>();
List<string> nofiles = new List<string>();
foreach (var drives in DriveInfo.GetDrives())
{
var filez = Directory.GetFiles(drives.Name,"*",SearchOption.AllDirectories);
foreach (string f in filez)
{
if (f.StartsWith(@"C:\Windows"))
{
}
else if (f.StartsWith(@"C:\Config.Msi"))
{
}
else if (f.StartsWith(@"C:\Program Files"))
{
}
else if (f.StartsWith(@"C:\Program Files (x86)"))
{
}
else if (f.StartsWith(@"C:\DumpStack.log"))
{
}
else if(f.StartsWith(@"C:\$Recycle.Bin\S-1-5-18"))
{
}
else if(f.StartsWith(@"C:\Documents and Settings"))
{
}
else
{
files.Add(f);
}
}
foreach (string fl in files)
{
var c = Path.GetFullPath(fl);
Console.WriteLine(c);
Console.ReadKey();
}
Console.ReadKey();
}
}
CodePudding user response:
Direct access almost always ends with access denied somewhere you should specify the search rules more precisely with the enumeration options, like below:
foreach (var drive in DriveInfo.GetDrives())
{
if (drive.IsReady == false)
{
continue;
}
var filez = Directory.GetFiles(drive.Name, "*", new EnumerationOptions
{
AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
IgnoreInaccessible = true,
RecurseSubdirectories = true,
ReturnSpecialDirectories = true,
});
// TODO: implement the rest of your code hier ...
}
where the FileAttributes.Hidden is not realy required. ... hope that helps!
CodePudding user response:
With Directory.GetFiles(drives.Name,"*",SearchOption.AllDirectories);
you already iterate trough all the directories. The filtering is done afterwards and only used to decide whether you add the directory name (that you already have!) to your list.
To filter the way you want, you need to implement the recursion yourself and catch the exception on each step.