質問

I need to load files from a directory with search option. I created two search patterns, first I must find files begining with "Client" and without the "_delete" extension.

The second search must find files begining with "Client" and with extension "_delete".

I implemented test code, but did not find files.

string mask_not_like = @"Client*[^_delete\s].xlsx";
string mask = "Client*_delete.xlsx";

path1 = "c:\Client_Test.xlsx";
path2 = "c:\Client_Test_delete.xlsx";

var searchPattern1 = new Regex(mask_not_like, RegexOptions.IgnoreCase);
var searchPattern2 = new Regex(mask, RegexOptions.IgnoreCase);

var files1 = Directory.GetFiles(path1).Where(f => searchPattern1.IsMatch(f));
var files2 = Directory.GetFiles(path1).Where(f => searchPattern2.IsMatch(f));
役に立ちましたか?

解決 2

Why even bother with regex?

var clientFiles = Directory.GetFiles("C:\\", "Client*.xlsx");
var clientFilesWithDelete = clientFiles.Where(clientFile => clientFile.EndsWith("_delete.xlsx"));
var clientFilesWithoutDelete = clientFiles.Except(clientFilesWithDelete);

他のヒント

Well, the first problem is that you're passing file paths to a method which expects a directory.

path1 = "c:\Client_Test.xlsx";
// path one is not a directory...
var files1 = Directory.GetFiles(path1).Where(f => searchPattern1.IsMatch(f));

That should throw an IOException since path1 is a file name.

Next, you're overcomplicating things. No regex is required (or warranted).

You have two cases; files which begin with "Client" and end in "_delete", and those which begin with "Client" and do not. "Client" is common to both, so, just grab all files which begin with client, next find those that end in "_delete", and the rest are those which do not end in "_delete".

var allFiles = Directory.GetFiles(path, "Client*.xlsx");
var endInDdelete = allFiles.Where(f => Path.GetExtension(f) == "._delete");
var doNotEndInDelete = allFiles.Except(endInDelete);

EDIT: I just noticed that you erroneously say that the extension is "_delete", when in reality, it's just the end of the file name. So...

var allFiles = Directory.GetFiles(path, "Client*.*");
var endInDdelete = allFiles.Where(f => Path.GetFileNameWithoutExtension(f).EndsWith("_delete");
var doNotEndInDelete = allFiles.Except(endInDelete);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top