Listing Files in a Directory using .Net


Level: Beginner

DirectoryInfo class is useful for creating, moving, and enumerating through directories and subdirectories.

for example, you can make a new directory like this,

DirectoryInfo di = new DirectoryInfo(@”c:\TestDir”);
if (!di.Exists)
di.Create();

FileInfo class provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

Here is a simple code snippet to list all files in a given directory (example takes a directory path as input and returns an array list of files)

private ArrayList GetFileList(string inputDir)
{
ArrayList fileList = new ArrayList();
DirectoryInfo di = new DirectoryInfo(inputDir);
//GetFiles method accepts filter patterns like “*.xml”
FileInfo[] fArray = di.GetFiles(“*.*”);foreach(FileInfo fi in fArray)
{
fileList.Add(fi);
}
return (fileList);

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s