Workaround for a bug in .NET’s Directory.GetFiles()

Calling Directory.GetFiles() with a UNC path and passing a file spec (like *.doc) will cause an IOException stating "There are no more files.". If you pass *.* as the file spec, the method successfully returns the list of files (including .doc files). So to work around this bug, you have to do the filtering yourself on the string array returned when passing *.*. This can be done with the following code:

/// <summary>
/// Gets the list files in a directory that meet a file specification.
/// </summary>
/// <param name="directory">The directory.</param>
/// <param name="fileSpec">The file spec (e.g. *.* or *.doc).</param>
/// <param name="searchOption">Whether to search sub-directories.</param>
/// <returns>The list of files found.</returns>
/// <remarks>
/// This method works around a bug in .NET's Directory.GetFiles() method.
/// An IOException is incorrectly thrown when use a file spec other than *.* when searching a UNC path.
/// The Solution is to pass *.* and do the filtering yourself, which is what this method does.  
/// </remarks>
public IEnumerable<string> GetFiles(string directory, string fileSpec, SearchOption searchOption)
   string[] files = Directory.GetFiles(directory, "*.*", searchOption);

   var pattern = String.Format(".*{0}", fileSpec.Replace(".", "\\.").Replace("*", ".*"));

   var fileSpecRegex = new Regex(pattern, RegexOptions.IgnoreCase);

   var matchingFiles = from o in files
			where fileSpecRegex.IsMatch(o)
			select o;

   return matchingFiles;

See also: MSDN discussion on this.