Microsoft TechNet
0 out of 1 rated this helpful - Rate this topic

DirectoryInfo.GetFiles Method (String, SearchOption)

Updated: May 2010

Returns a file list from the current directory matching the given search pattern and using a value to determine whether to search subdirectories.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
public FileInfo[] GetFiles(
	string searchPattern,
	SearchOption searchOption
)

Parameters

searchPattern
Type: System.String
The search string. For example, "System*" can be used to search for all directories that begin with the word "System".
searchOption
Type: System.IO.SearchOption
One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories.

Return Value

Type: System.IO.FileInfo[]
An array of type FileInfo.
Exception Condition
ArgumentException

searchPattern contains one or more invalid characters defined by the GetInvalidPathChars method.

ArgumentNullException

searchPattern is null.

ArgumentOutOfRangeException

searchOption is not a valid SearchOption value.

DirectoryNotFoundException

The path is invalid (for example, it is on an unmapped drive).

SecurityException

The caller does not have the required permission.

If there are no files in the DirectoryInfo, this method returns an empty array.

The following wildcard specifiers are permitted in searchPattern.

Wildcard character

Description

*

Zero or more characters.

?

Exactly one character.

The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.

Wildcards are permitted. For example, the searchPattern string "*.txt" searches for all file names having an extension of "txt". The searchPattern string "s*" searches for all file names beginning with the letter "s". If there are no files, or no files that match the searchPattern string in the DirectoryInfo, this method returns an empty array.

Note Note

When using the asterisk wildcard character in a searchPattern (for example, "*.txt"), the matching behavior varies depending on the length of the specified file extension. A searchPattern with a file extension of exactly three characters returns files with an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern. A searchPattern with a file extension of one, two, or more than three characters returns only files with extensions of exactly that length that match the file extension specified in the searchPattern. When using the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files in a directory, "file1.txt" and "file1.txtother", a search pattern of "file?.txt" returns only the first file, while a search pattern of "file*.txt" returns both files.

The following list shows the behavior of different lengths for the searchPattern parameter:

  • "*.abc" returns files having an extension of.abc,.abcd,.abcde,.abcdef, and so on.

  • "*.abcd" returns only files having an extension of.abcd.

  • "*.abcde" returns only files having an extension of.abcde.

  • "*.abcdef" returns only files having an extension of.abcdef.

Note Note

Because this method checks against file names with both the 8.3 file name format and the long file name format, a search pattern similar to "*1*.txt" may return unexpected file names. For example, using a search pattern of "*1*.txt" will return "longfilename.txt" because the equivalent 8.3 file name format would be "longf~1.txt".

This method pre-populates the values of the following FileInfo properties:

  1. Attributes

  2. CreationTime

  3. CreationTimeUtc

  4. LastAccessTime

  5. LastAccessTimeUtc

  6. LastWriteTime

  7. LastWriteTimeUtc

  8. Length

The following example lists all of the directories and files that begin with the letter "c" in "c:\".


using System;
using System.IO;

class App
{
    public static void Main()
    {
        // Specify the directory you want to manipulate.
        string path = @"c:\";
        string searchPattern = "c*";

        DirectoryInfo di = new DirectoryInfo(path);
        DirectoryInfo[] directories = 
            di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);

        FileInfo[] files = 
            di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);

        Console.WriteLine(
            "Directories that begin with the letter \"c\" in {0}", path);
        foreach (DirectoryInfo dir in directories)
        {
            Console.WriteLine(
                "{0,-25} {1,25}", dir.FullName, dir.LastWriteTime);
        }

        Console.WriteLine();
        Console.WriteLine(
            "Files that begin with the letter \"c\" in {0}", path);
        foreach (FileInfo file in files)
        {
            Console.WriteLine(
                "{0,-25} {1,25}", file.Name, file.LastWriteTime);
        }
    } // Main()
} // App()


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Date

History

Reason

May 2010

Updated remarks.

Information enhancement.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Workaround for the 8.3 filename standard AKA Shortfilename AKA SFN

I've made three extension for the DirectoryInfo object, so that the match when using something like "*.abc" ONLY returns files with abc extension.

/// <summary>
/// Returns a file list from the current directory matching the given searchPattern and using a value to determine whether to search subdirectories.
/// This is as fix for 8.3 filename standard. more information here: http://msdn.microsoft.com/en-us/library/ms143327.aspx
/// </summary>
/// <param name="directoryinfo">object to use.</param>
/// <param name="searchPattern">The search string, such as "System*", used to search for all directories beginning with the word "System".</param>
/// <param name="searchOption">One of the values of the System.IO.SearchOption enumeration that specifies whether the search operation should include only the current directory or should include all subdirectories.</param>
/// <returns>An array of type System.IO.FileInfo.</returns>
/// <exception cref="System.ArgumentNullException">searchPattern is null.</exception>
/// <exception cref="System.IO.DirectoryNotFoundException">The path is invalid, such as being on an unmapped drive.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>http://msdn.microsoft.com/en-us/library/ms143327.aspx</remarks>
public static FileInfo[] GetFilesFixed(this DirectoryInfo directoryinfo, string searchPattern, SearchOption searchOption)
{
if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
return directoryinfo.GetFiles(searchPattern, searchOption).ToList().FindAll(F => F.Extension.Length == 4).ToArray();
return directoryinfo.GetFiles(searchPattern, searchOption);
}

/// <summary>
/// Returns a file list from the current directory matching the given searchPattern.
/// This is as fix for 8.3 filename standard. more information here: http://msdn.microsoft.com/en-us/library/ms143327.aspx
/// </summary>
/// <param name="directoryinfo">object to use.</param>
/// <param name="searchPattern">The search string, such as "*.txt".</param>
/// <returns>An array of type System.IO.FileInfo.</returns>
/// <exception cref="System.ArgumentNullException">searchPattern is null.</exception>
/// <exception cref="System.IO.DirectoryNotFoundException">The path is invalid, such as being on an unmapped drive.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>http://msdn.microsoft.com/en-us/library/ms143327.aspx</remarks>
public static FileInfo[] GetFilesFixed(this DirectoryInfo directoryinfo, string searchPattern)
{
if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
return directoryinfo.GetFiles(searchPattern).ToList().FindAll(F => F.Extension.Length == 4).ToArray();
return directoryinfo.GetFiles(searchPattern);
}

/// <summary>
/// Retrieves an array of strongly typed System.IO.FileSystemInfo objects representing the files and subdirectories matching the specified search criteria.
/// This is as fix for 8.3 filename standard. more information here: http://msdn.microsoft.com/en-us/library/ms143327.aspx
/// </summary>
/// <param name="directoryinfo">object to use.</param>
/// <param name="searchPattern">The search string, such as "System*", used to search for all directories beginning with the word "System".</param>
/// <returns>An array of strongly typed FileSystemInfo objects matching the search criteria.</returns>
/// <exception cref="System.ArgumentNullException">searchPattern is null.</exception>
/// <exception cref="System.IO.DirectoryNotFoundException">The path is invalid, such as being on an unmapped drive.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
public static FileSystemInfo[] GetFileSystemInfosFixed(this DirectoryInfo directoryinfo, string searchPattern)
{
if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
return directoryinfo.GetFileSystemInfos(searchPattern).ToList().FindAll(F => F.Extension.Length == 4).ToArray();
return directoryinfo.GetFiles(searchPattern);
}
IO operations on individual files
Question: does this method perform IO operations on individual files? or are these file names read from directory data?
Count or Length returns different values when executed in Windows7 SP1 and Windows2003 SP2
Count or Length returns different values when executed in Windows7 SP1 and Windows2003 SP2.

When run in windows 7, it gives correct values but not in Windows 2003. Any Idea??? It should work same way in both OS right?