具有多个特定扩展的GetFiles c#
我想要有扩展名为xls和xlsx的Excel文件,以及来自特定目录的FileInfo对象,所以我放下面的代码
System.IO.FileInfo[] files = null; System.IO.DirectoryInfo dirInfo; dirInfo = new System.IO.DirectoryInfo(this.tbFolderTo.Text); string[] extensions = new[] { "*.xls", "*.xlsx" }; List _searchPatternList = new List(extensions); List fileList = new List(); foreach (string ext in _searchPatternList) { foreach (string subFile in Directory.GetFiles(this.tbFolderTo.Text, ext)) { fileList.Add(subFile); } } foreach (string file in fileList) { this.lbFileNamesTo.Items.Add(file); }
但是通过使用像filexp2.xlsq或filexp.xlsa这样的虚假文件进行测试的问题,我在列表框中看到这些文件以显示找到的文件列表,在代码中我限制了对xls和xlsx的扩展我不知道为什么我看到结果中的这些文件
结果我没看到我打的代码和这段代码之间的任何区别
System.IO.FileInfo[] files = null; System.IO.DirectoryInfo dirInfo; dirInfo = new System.IO.DirectoryInfo(this.tbFolderTo.Text); files = dirInfo.GetFiles("*.xls*");
感谢帮助
来自MSDN:
在searchPattern中使用星号通配符(例如“* .txt”)时,扩展名正好长度为三个字符时的匹配行为与扩展名长度多于或少于三个字符时的匹配行为不同。 具有正好三个字符的文件扩展名的searchPattern将返回扩展名为三个或更多字符的文件,其中前三个字符与searchPattern中指定的文件扩展名匹配。 文件扩展名为一个,两个或三个以上字符的searchPattern仅返回扩展名与searchPattern中指定的文件扩展名完全匹配的文件。 使用问号通配符时,此方法仅返回与指定文件扩展名匹配的文件。 例如,给定两个文件“file1.txt”和“file1.txtother”,在目录中,“file?.txt”的搜索模式只返回第一个文件,而搜索模式为“file * .txt”。返回两个文件。
https://msdn.microsoft.com/it-it/library/wz42302f.aspx
如果您使用.NET 4.0,此代码将起作用,并且与GetFiles()
相比将提高内存使用率:
string[] patterns = new { ".xls", ".xlsx" }; return patterns.AsParallel().SelectMany(p => Directory.EnumerateFiles(path, p, SearchOption.AllDirectories));
资料来源:
如果你不想要隐式的非精确匹配,你可以随时回退到WinAPI PathMatchSpec
函数,它几乎用于处理整个系统中的通配符,而不会像Directory.GetFiles
那样令人烦恼(这是一个不一致!)
public static class DirectoryEx { [DllImport("shlwapi.dll", CharSet = CharSet.Auto)] private static extern bool PathMatchSpec(string file, string spec); public static IEnumerable GetFilesExact(string path, string searchPattern) { var files = Directory.GetFiles(path, searchPattern).ToList(); foreach (var file in files) { if (PathMatchSpec(file, searchPattern)) { yield return file; } } } }
这样你仍然可以使用通配符,但是以可预测的方式。 所以将内循环更改为:
foreach (string subFile in DirectoryEx.GetFilesExact(this.tbFolderTo.Text, ext)) { fileList.Add(subFile); }
你很高兴。
由于@qwertoyo已经非常正确地引用了MSDN中的说明,说明为什么你有问题,我想也许我会尝试给你另一个解决方案。
您可以枚举目录中的所有文件(通过使用EnumerateFiles
代替GetFiles
您不需要等待整个目录)并仅提取符合您要求的文件:
string[] extensions = new[] { ".xls", ".xlsx" }; var excelFiles = Directory.EnumerateFiles(this.tbFolderTo.Text) .Where(f => extensions.Contains(File.GetExtension(f)));
如果使用.NET 3.5或更早版本,则必须回退到GetFiles
解决方案,但是对于大目录,它会很慢!
上述就是C#学习教程:具有多个特定扩展的GetFiles c#分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
string[] extensions = new[] { ".xls", ".xlsx" }; var excelFiles = Directory.GetFiles(this.tbFolderTo.Text) .Where(f => extensions.Contains(Path.GetExtension(f)));
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/962315.html