[英]How can i get all files on disk with a specific extension using 'Directory.getFiles' and save them in a list
I'm doing a console project whose goal is to search the entire disk for all files with the extension '.config' 我正在做一个控制台项目,其目标是在整个磁盘上搜索扩展名为“.config”的所有文件
I've tried something like: 我尝试过类似的东西:
foreach (string file in Directory.GetFiles("C:\\", "*.config", SearchOption.AllDirectories))
{
Console.WriteLine(file);
Console.ReadLine();
}
but gave me an error "denied access to path (...)". 但给了我一个错误“拒绝访问路径(...)”。
On the internet I found this code: 在互联网上,我发现这个代码:
Stack<string> pending = new Stack<string>();
pending.Push("C:\\");
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, "*.config");
}
catch { }
if (next != null && next.Length != 0)
foreach (var file in next)
{
Console.WriteLine(file);
Console.ReadLine();
}
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
but it just shows the path clicking always in 'enter' and I want to save those files/path in a list. 但它只显示总是在'enter'中单击的路径,我想在列表中保存这些文件/路径。
Someone can help? 有人可以帮忙吗?
Replace the lines 替换线
Console.WriteLine(file);
Console.ReadLine();
with a method to store them in a list. 用一种方法将它们存储在列表中。
For example 例如
foundFiles.Add(file);
Then when the method is done, you can read all found file paths from this list. 然后,当方法完成后,您可以从此列表中读取所有找到的文件路径。
Notes: 笔记:
This will not yield all files on the system that match the filter. 这不会产生系统上与过滤器匹配的所有文件。
Only files where your application has access to their respective directory are found this way. 只有这样才能找到应用程序可以访问其各自目录的文件。
For example the Windows directory and user directories of other users are usually protected. 例如,其他用户的Windows目录和用户目录通常受到保护。 (assuming you run on Windows) (假设您在Windows上运行)
Keep in mind, that some files might be protected independently of their directory. 请记住,某些文件可能会受到独立于其目录的保护。
So when trying to read them, also consider the fact, that the read might fail. 因此,在尝试阅读它们时,还要考虑读取可能失败的事实。
Just encompass the read with a try catch. 只是用try catch包含读取。
There are two things you can do to improve that code: 您可以采取两项措施来改进该代码:
Directory.EnumerateFiles()
and Directory.EnumerateDirectories()
to avoid making a copy of the names of all the files in each directory. 使用Directory.EnumerateFiles()
和Directory.EnumerateDirectories()
可以避免复制每个目录中的所有文件的名称。 IEnumerable<string>
to make it easier to consume. 使IEnumerable<string>
方法的返回类型更容易使用。 We also need to be very careful about exceptions caused by attempting to access protected files and directories. 我们还需要非常小心尝试访问受保护文件和目录所导致的异常。 The code below is also complicated by the fact that you're not allowed to yield return
from inside a try/catch
block, so we have to rearrange the code somewhat. 下面的代码也很复杂,因为你不允许从try/catch
块中yield return
,所以我们必须稍微重新排列代码。
(Also note that we have to dispose the enumerator returned from .GetEnumerator()
; normally this is done automatically when you use foreach
, but in this case we can't - because of having to avoid doing yield return
in a try/catch
- so we have to use using
to dispose it.) (另请注意,我们必须处理从.GetEnumerator()
返回的枚举器;通常这是在使用foreach
时自动完成的,但在这种情况下我们不能 - 因为必须避免在try/catch
执行yield return
-所以我们必须使用using
处置它。)
Here's a modification of your original code to do this: 以下是对原始代码的修改:
public static IEnumerable<string> GetFiles(string root, string spec)
{
var pending = new Stack<string>(new []{root});
while (pending.Count > 0)
{
var path = pending.Pop();
IEnumerator<string> fileIterator = null;
try
{
fileIterator = Directory.EnumerateFiles(path, spec).GetEnumerator();
}
catch {}
if (fileIterator != null)
{
using (fileIterator)
{
while (true)
{
try
{
if (!fileIterator.MoveNext()) // Throws if file is not accessible.
break;
}
catch { break; }
yield return fileIterator.Current;
}
}
}
IEnumerator<string> dirIterator = null;
try
{
dirIterator = Directory.EnumerateDirectories(path).GetEnumerator();
}
catch {}
if (dirIterator != null)
{
using (dirIterator)
{
while (true)
{
try
{
if (!dirIterator.MoveNext()) // Throws if directory is not accessible.
break;
}
catch { break; }
pending.Push(dirIterator.Current);
}
}
}
}
}
As an example, here's how you could use a console app to list all the accessible ".txt" files on the "C:\\" drive: 例如,以下是如何使用控制台应用程序列出“C:\\”驱动器上所有可访问的“.txt”文件:
static void Main()
{
foreach (var file in GetFiles("C:\\", "*.txt"))
{
Console.WriteLine(file);
}
}
关于错误“拒绝访问路径(...)”,有时您必须以管理员身份运行Visual Studio才能访问C:\\驱动器中的某些文件夹。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.