C# Directory EnumerateFiles(String, String, SearchOption)

Description

Directory EnumerateFiles(String, String, SearchOption) Returns an enumerable collection of file names that match a search pattern in a specified path, and optionally searches subdirectories.

Syntax

Directory.EnumerateFiles(String, String, SearchOption) has the following syntax.


public static IEnumerable<string> EnumerateFiles(
  string path,/*  www  .j  a  v a  2s  .  c o m*/
  string searchPattern,
  SearchOption searchOption
)

Parameters

Directory.EnumerateFiles(String, String, SearchOption) has the following parameters.

  • path - The directory to search.
  • searchPattern - The search string to match against the names of files in path.
  • searchOption - One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.
  • searchOption - The default value is TopDirectoryOnly.

Returns

Directory.EnumerateFiles(String, String, SearchOption) method returns <

Example

The following example shows how to retrieve all the text files in a directory and its subdirectories, and move them to a new directory.


//from   w w  w  . ja  va  2s . c o m
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string sourceDirectory = @"C:\current";
        string archiveDirectory = @"C:\archive";
 
        var txtFiles = Directory.EnumerateFiles(sourceDirectory, 
                      "*.txt", SearchOption.AllDirectories);
 
        foreach (string currentFile in txtFiles)
        {
            string fileName = currentFile.Substring(sourceDirectory.Length + 1);
            Directory.Move(currentFile, Path.Combine(archiveDirectory, fileName));
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter