foreach(DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
try
{
string[] files = Directory.GetFiles(d.RootDirectory.ToString(), fileName, SearchOption.AllDirectories);
foreach(string file in files)
{
Console.WriteLine(file);
}
}
catch(exception ex)
{
}
}
It seems simple enough, except I keep getting System.unauthorizedaccessexception
.
So I tried to write a linq statement to check all files that don't have system flag and return it to a list.
var folderFound = new DirectoryInfo(d.RootDirectory.ToString())
.GetFiles()
.Where(f => !f.Attributes.HasFlag(FileAttributes.System) && f.Name == fileName)
.Select(f => f.Name)
.ToList();
But its not working quite right. It wont check all directories as well. How do i solve my problem?
I did not solve my problem Couldnt use a linq statement
foreach(DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
Stack<DirectoryInfo> dirstack = new Stack<DirectoryInfo>();
dirstack.Push(new DirectoryInfo(d.RootDirectory.ToString()));
while(dirstack.Count > 0)
{
DirectoryInfo current = dirstack.Pop();
foreach (DirectoryInfo di in current.GetDirectories())
{
if((di.Attributes & FileAttributes.System) != FileAttributes.System)
{
dirstack.Push(di);
}
}
foreach (FileInfo f in current.GetFiles())
{
if (f.Name == fileName)
{
fList.Add(f);
}
}
}
I am trying the one in the comments below, but as soon as i hit
var dirs = di.EnumerateDirectories();
it is throwing System.UnauthorizedAccessException. I don't have ability to even read if I have ability to manipulate. Is my guess at what is going on.