[英]How to get specific type of files from a specific directory in a given path in an array in c#?
[英]How to check if a type of files exists in specific folder of a specific drive and return only the directory path within less time in C#
我想从D驱动器中找到所有文档文件。 我已经写了下面的代码,但是太费时间了。 同样由于在获取数据上花费了更多时间,这给了我一个例外。 为了减少时间,我只想检查一下:
即使该文件夹中存在一种文件类型->返回文件夹的路径
这样就不必检查同一文件夹示例中的所有文件类型:-
如果C:\\Program Files\\Notepad++
具有readme.txt
和其他文本文件。 一旦检测到该文件夹中的第一个文本文件,它就必须返回: C:\\Program Files\\Notepad++
我在文件中使用的代码
List<string> mediaExtensions = new List<string>{"txt", "pdf"};
List<string> filesFound = new List<string>();
void DirSearch(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, "*.*"))
{
if(mediaExtensions.Contains(Path.GetExtension(f).ToLower()))
filesFound.Add(f);
}
DirSearch(d);
}
}
Update1:检查此链接确实使我有了递归的想法,并忽略了文件,但没有使搜索文件所花费的时间最少。
Update2:-在上面的代码中,我使用了if(mediaExtensions.Contains(Path.GetExtension(f).ToLower()))
即使文件夹中存在文件,我也不会得到任何值
第一个解决方案:(.Net 4.0)
这可能会加快速度:
DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
return dirInfo.EnumerateDirectories()
.AsParallel()
.SelectMany(di => di.EnumerateFiles("*.*", SearchOption.AllDirectories));
}
第二个解决方案:(。Net 3.5和4.0)
如果那不帮助检查基于WinAPI函数的Faster Directory Enumerator
资料来源: http : //www.codeproject.com/Articles/38959/A-Faster-Directory-Enumerator
Win Api功能: https : //msdn.microsoft.com/zh-cn/library/aa364428%28v=vs.85%29.aspx
您可以使用Directory.GetFiles()
方法来递归查找文件。 选中选项,您可以对其进行调整以适合您的需求,而无需亲自遍历目录:
用这个:
foreach (string f in Directory.GetFiles(d, "*.txt"))
{
// return ".txt file found in d
List<string> mediaExtensions = new List<string>{"txt", "pdf"};
List<string> filesFound = new List<string>();
void DirSearch(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, "*.*"))
{
if(mediaExtensions.Contains(Path.GetExtension(f).ToLower()))
filesFound.Add(f);
//you said you also need the path of the directory, add it from here
break;
}
DirSearch(d);
}
}
当添加f参数时,还尝试从外部foreach中添加d 1,您的要求是添加包含至少一个具有所需扩展名的文件的文件夹。
编辑1
遇到文档和设置时,您必须使用
var mydocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.