当前位置: 首页 > 编程语言 > C#

在C#中使用Directory.GetFiles和正则表达式?

时间:2023-04-10 18:03:46 C#

在C#中使用Directory.GetFiles和正则表达式?我有这段代码:string[]files=Directory.GetFiles(path,"...",SearchOption.AllDirectories)我想要的只是返回不是p_和t_p_以及扩展名png或jpg或gif文件。我该怎么办?默认情况下,Directory.GetFiles不支持RegEx,您可以在文件列表中按RegEx进行过滤。查看此列表:Regexreg=newRegex(@"^^(?!p_|t_).*");varfiles=Directory.GetFiles(yourPath,"*.png;*.jpg;*.gif").Where(path=>reg.IsMatch(path)).ToList();您不能将正则表达式粘贴到参数中,它只是一个简单的字符串过滤器。尝试使用LINQ过滤掉。varfiles=Directory.GetFiles(path,"*.*",SearchOption.AllDirectories).Where(s=>s.EndsWith(".jpg")||s.EndsWith(".png")).Where(s=>s.StartsWith("p_")==false&&s.StartsWith("t_")==false)尝试使用此代码搜索每个驱动器:Directory.GetFiles使用正则表达式?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——DriveInfo[]drives=DriveInfo.GetDrives();foreach(DriveInfodriveindrives){if(drive.RootDirectory.Exists){DirectoryInfodarr=newDirectoryInfo(drive.RootDirectory.FullName);DirectoryInfo[]ddarr=darr.GetDirectories();foreach(DirectoryInfodddarrinddarr){if(dddarr.Exists){try{Regexregx=newRegex(@"^(?!p_|t_)");FileInfo[]f=dddarr.GetFiles().Where(path=>regx.IsMatch(path));列出myFiles=newList();foreach(FileInfoffinf){if(ff.Extension=="*.png"||ff.Extension=="*.jpg"){myFiles.Add(ff);Console.WriteLine("文件:{0}",ff.FullName);Console.WriteLine("文件类型:{0}",ff.Extension);}}}catch{Console.WriteLine("文件:{0}","拒绝");}}}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: