[英]Directory.GetFiles() method in C#
Recently i am working on my class assignment, in which i need to get multiple files from a directory with different extensions. 最近,我正在做班级作业,其中我需要从具有不同扩展名的目录中获取多个文件。 I use this code: 我使用以下代码:
List<string> Extensions =new List<string>() ;
Extensions.InsertRange(3, new string[] { "*.txt", "*.htt","*.bat"});
FolderBrowserDialog _fBrowser = new FolderBrowserDialog();
if (_fBrowser.ShowDialog() == DialogResult.OK)
{
tbPath.Text = _fBrowser.SelectedPath;
foreach (var item in Extensions)
{
SearchFiles(item);
}
}
In SearchFile() i use this line to search a file on base of extension: 在SearchFile()中,我使用以下行在扩展名的基础上搜索文件:
private void SearchFile(string extension)
{
Files = Directory.GetFiles(tbPath.Text, extension).ToList();
}
If I want to search files with .txt , .htt and .bat extensions from a directory and if there is not any file with .txt extension in current directory then it cause an exception that "Path is not legal" but i want to continue search on base of next extension( .htt ). 如果我要从目录中搜索扩展名为.txt , .htt和.bat的文件,并且如果当前目录中没有任何扩展名为.txt的文件,则会导致出现“路径不合法”的异常,但我想继续在下一个扩展名( .htt )的基础上搜索。 What i can do? 我可以做什么?
You can use something like this: 您可以使用如下形式:
var extensions = new string[] { ".txt", ".htt", ".bat" };
var foundFiles = Directory.EnumerateFiles(path, "*.*")
.Where(file => extensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase));
Use try catch block 使用try catch块
List<string> Extensions =new List<string>() ;
Extensions.InsertRange(3, new string[] { "*.txt", "*.htt","*.bat"});
FolderBrowserDialog _fBrowser = new FolderBrowserDialog();
if (_fBrowser.ShowDialog() == DialogResult.OK)
{
tbPath.Text = _fBrowser.SelectedPath;
foreach (var item in Extensions)
{
try{
SearchFiles(item);
}
catch(Exception ex) { };
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.