-1

I am using the following C# code to filter a directory containing multiple files:

files = Directory.GetFiles(SourceDatafiles, @"2022*.txt",SearchOption.TopDirectoryOnly);

The directory contains multiple files for instance files like: 2022-07-21-14.txt
2017-2-2-0.txt

The result of the filter is wrong: It also filters the second file name as a valid name. But it does not contain "2022" !? Any idea what's wrong?

freeck
  • 1
  • 1
  • https://en.wikipedia.org/wiki/8.3_filename – Hans Passant Jul 21 '22 at 17:24
  • Please provide the content of the directory you are using this code on (i.e. output of `DIR /x | findtr "2022"` ) – Luuk Jul 21 '22 at 19:13
  • 10/02/2014 08:04 AM 4,265 202261~1.TXT 2014-10-1-22.txt 10/20/2014 09:01 AM 4,265 202205~1.TXT 2014-10-20-7.txt, the output contains "2022" :). Directory resides on m:/ disk. Same result in the c:/ directory. – freeck Jul 22 '22 at 08:55

2 Answers2

0

Perhaps you could share more information on your environment, DotNet framework version, OS etc.

When I run the below code using DotNet 6 on Windows I get the expected results, namely it only prints the file 2022-07-14.txt

string SourceDatafiles = @"C:\Temp\Test";
var files = Directory.GetFiles(SourceDatafiles, @"2022*.txt", SearchOption.TopDirectoryOnly);

foreach (var file in files)
{
    Console.WriteLine(file);
}
  • Windows 10 HOME, .NETFramework,Version=v4.5", Microsoft Visual Studio Community 2019, NTFS. – freeck Jul 22 '22 at 09:29
  • Problem still exits after installing .NET6.0. BUT: I got it working using both platforms using only a small amount of files in the source-directory. In that case it workes as intended. In my case the source-directory contains more than 5000 files , then the unexpected result show up!? – freeck Jul 22 '22 at 13:44
  • Correction: 75000 files; no exceptions occurred. – freeck Jul 22 '22 at 14:21
  • https://stackoverflow.com/a/39753445/19595774 I will give this a try, a better approach I guess. Still wondering why the wild-card filter did not work as expected. – freeck Jul 23 '22 at 07:43
0

See also: https://stackoverflow.com/a/39753445/19595774

int count1 = 0;
int count2 = 0;
string pattern = "2022"; 
foreach (var file in Directory.EnumerateFiles(dir))
{
    if (file.Contains("2022"))
        Console.WriteLine("Index:" + count1++ + "Name:" + file); 
    /* OR */
    if (Regex.IsMatch(file, pattern) )
        Console.WriteLine("Index:" + count2++ + "Name:" + file);
}

Enumeration works fine. I think a better approach than Directory.GetFiles(SourceDatafiles, @"2022*.txt",SearchOption.TopDirectoryOnly). Still wondering why the wild-card filter did not work as expected.

mcky
  • 823
  • 2
  • 7
  • 20
freeck
  • 1
  • 1