我有這樣的代碼:在C#中使用Directory.GetFiles與正則表達式?
string[] files = Directory.GetFiles(path, "......", SearchOption.AllDirectories)
我想要的是返回只不與p_
和t_
開始,具有擴展名PNG或JPG或GIF文件。我將如何做到這一點?
我有這樣的代碼:在C#中使用Directory.GetFiles與正則表達式?
string[] files = Directory.GetFiles(path, "......", SearchOption.AllDirectories)
我想要的是返回只不與p_
和t_
開始,具有擴展名PNG或JPG或GIF文件。我將如何做到這一點?
Directory.GetFiles
不支持RegEx
默認情況下,你可以做的是RegEx
文件列表進行過濾。在此房源看看:
Regex reg = new Regex(@"^^(?!p_|t_).*");
var files = Directory.GetFiles(yourPath, "*.png; *.jpg; *.gif")
.Where(path => reg.IsMatch(path))
.ToList();
您不能將Regex粘貼到參數中,它只是一個簡單的字符串過濾器。嘗試使用LINQ來代替事後過濾。
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".jpg") || s.EndsWith(".png"))
.Where(s => s.StartsWith("p_") == false && s.StartsWith("t_") == false)
試試這個代碼,搜索每個驅動器,以及:
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.RootDirectory.Exists)
{
DirectoryInfo darr = new DirectoryInfo(drive.RootDirectory.FullName);
DirectoryInfo[] ddarr = darr.GetDirectories();
foreach (DirectoryInfo dddarr in ddarr)
{
if (dddarr.Exists)
{
try
{
Regex regx = new Regex(@"^(?!p_|t_)");
FileInfo[] f = dddarr.GetFiles().Where(path => regx.IsMatch(path));
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo ff in f)
{
if (ff.Extension == "*.png " || ff.Extension == "*.jpg")
{
myFiles.Add(ff);
Console.WriteLine("File: {0}", ff.FullName);
Console.WriteLine("FileType: {0}", ff.Extension);
}
}
}
catch
{
Console.WriteLine("File: {0}", "Denied");
}
}
}
}
}
這裏[http://stackoverflow.com/questions/1601241/c-sharp看看-regex-matching-file-names-according-to-a-specific-naming-pattern] [1] [1]:http://stackoverflow.com/questions/1601241/c-sharp-regex-matching -file-names-according-to-a-specific-naming-pattern – f0rza
@ f0rza,'[a link](http:// url)';-) – Qtax
[如何根據C#中的RegEx查找文件] (HTTP:// stackov erlow.com/questions/2809604/how-to-find-files-according-regex-in-c-sharp) – Christian