Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


Fixing Directory.GetFiles to return exact match on extension only
Directory.GetFiles("*.xls") matches BOTH xls and xlsx, due to it only matching on the first three characters of the extension. Here is a generic fix for all file types.

/// <summary>
/// Directory.GetFiles(*.ext) returns BOTH .ext files and .extXXX files (anything starting with the first 3 chars).
/// So if an exact extension was passed in, this method will exclude results which don't match the extension.
/// *.xls -> returns xls but not xlsx
/// *.xls* -> returns xls and xlsx
/// </summary>
/// <param name="directorySearchPattern"></param>
/// <param name="fileSearchPattern"></param>
/// <param name="searchOption"></param>
/// <returns></returns>
public static string[] GetFilesExact(string directorySearchPattern, string fileSearchPattern, SearchOption searchOption)
List<string> ret = new List<string>();
string ext = Path.GetExtension(fileSearchPattern);
bool exactExtensionSearch = !(ext.Contains("*")); // by default windows uses an inexact match search, ie .xls also matches .xlsx.
// We want to make sure if a full extension was provided with no wildcards, we use the exact matches only.
var files = Directory.GetFiles(directorySearchPattern, fileSearchPattern, searchOption);
foreach (var file in files)
if (!exactExtensionSearch ||
Path.GetExtension(file).Equals(ext, StringComparison.CurrentCultureIgnoreCase))
{ // ensure the extension matches the one passed if doing exact match.
return ret.ToArray();

Created By: amos 1/26/2016 4:44:13 PM
Updated: 1/26/2016 8:16:37 PM