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)
{
}
}
看起来很简单,除了我不断获得System.unauthorizedaccessexception
。
所以我尝试编写一个linq语句来检查所有没有系统标志的文件并将其返回到列表中。
var folderFound = new DirectoryInfo(d.RootDirectory.ToString())
.GetFiles()
.Where(f => !f.Attributes.HasFlag(FileAttributes.System) && f.Name == fileName)
.Select(f => f.Name)
.ToList();
但它的工作不正常。它也不会检查所有目录。我如何解决我的问题?
我没有解决我的问题无法使用linq语句
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);
}
}
}
我正在尝试下面评论中的那个,但是一击到
var dirs = di.EnumerateDirectories();
它正在抛出System.UnauthorizedAccessException。如果我有能力操作,我甚至没有能力阅读。我猜测是怎么回事。
答案 0 :(得分:1)
var folderFound = new DirectoryInfo(d.RootDirectory.ToString())
.GetFiles("*",SearchOption.AllDirectories)
.Where(f => !f.Attributes.HasFlag(FileAttributes.System) && f.Name == fileName)
.Select(f => f.Name)
.ToList();
更新 尝试这种递归方法。在stackoverflow上找到了某个地方。这会抓住并继续留下来。
public static List<string> GetAllAccessibleFiles(string rootPath, List<string> alreadyFound = null)
{
if (alreadyFound == null)
alreadyFound = new List<string>();
DirectoryInfo di = new DirectoryInfo(rootPath);
var dirs = di.EnumerateDirectories();
foreach (DirectoryInfo dir in dirs)
{
if (!((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden))
{
alreadyFound = GetAllAccessibleFiles(dir.FullName, alreadyFound);
}
}
var files = Directory.GetFiles(rootPath);
foreach (string s in files)
{
alreadyFound.Add(s);
}
return alreadyFound;
}