user3305198
user3305198

Reputation: 73

Get files by filename mask

fileNameMaskI need load files from directory by filename mask, if filename begin with "Table 1" work well, but if directory contain any files: "TestTable 1 someValue.xlsx" or "Test Table 1 someValue.xlsx" my mask not work.

If I change mask to "^(Table 1).*\.xlsx$" - Directory.GetFiles return all files with "Table 1", but I need return only files where file name start from "Table 1".

My test code:

 var fileNameMask = "(Table 1).*\\.xlsx";
 string path = @"c:\Temp\";
 Regex searchPattern = new Regex(fileNameMask);
 string[] files = Directory.GetFiles(path).Where(f => searchPattern.IsMatch(f)).ToArray(); 

Upvotes: 0

Views: 9716

Answers (3)

zrabzdn
zrabzdn

Reputation: 995

Try this mask:

string maskfile = @"[^\w\s](Table 1)(.*)(.xlsx)"; 

Upvotes: 0

binarymnl
binarymnl

Reputation: 153

Try code below:

private String[] GetFilesByMask(string pPath)
{
    Regex mask = new Regex(sFileMask.Replace(".", "[.]").Replace("*", ".*").Replace(".", "."));
    Return Directory.GetFiles(pPath).Where(f => mask.IsMatch(f)).ToArray();

}

Upvotes: 0

Maksim Gladkov
Maksim Gladkov

Reputation: 3079

Have you tried to use built-in functionality of GetFiles method?

Directory.GetFiles(path, "Test 1*.xlsx")

Upvotes: 7

Related Questions