C#: Using Directory.GetFiles to get files with fixed length

Jring Qin picture Jring Qin · Jun 8, 2009 · Viewed 7.6k times · Source

The directory 'C:\temp' has two files named 'GZ96A7005.tif' and 'GZ96A7005001.tif'. They have different length with the same extension. Now I run below code:

string[] resultFileNames = Directory.GetFiles(@"C:\temp", "????????????.tif");

The 'resultFileNames' return two items 'c:\temp\GZ96A7005.tif' and 'c:\temp\GZ96A7005001.tif'. But the Window Search will work fine. This is why and how do I get I want?

alt text

Answer

Matthew Flaschen picture Matthew Flaschen · Jun 8, 2009

For Directory.GetFiles, ? signifies "Exactly zero or one character." On the other hand, you could use DirectoryInfo.GetFiles, for which ? signifies "Exactly one character" (apparently what you want).

EDIT:

Full code:

string[] resultFileNames = (from fileInfo in new DirectoryInfo(@"C:\temp").GetFiles("????????????.tif") select fileInfo.Name).ToArray();

You can probably skip the ToArray and just let resultFileNames be an IEnumerable<string>.

People are reporting this doesn't work for them on MS .NET. The below exact code works for me with on Mono on Ubuntu Hardy. I agree it doesn't really make sense to have two related classes use different conventions. However, that is what the documentation (linked above) says, and Mono complies with the docs. If Microsoft's implementation doesn't, they have a bug:

using System;
using System.IO;
using System.Linq;

public class GetFiles
{
    public static void Main()
    {
        string[] resultFileNames = (from fileInfo in new DirectoryInfo(@".").GetFiles("????????????.tif") select fileInfo.Name).ToArray();
        foreach(string fileName in resultFileNames)
        {
            Console.WriteLine(fileName);
        }
    }
}