April 18, 2010

Listing Files in a Directory - C#

A portion of my senior design project is a media center component, so I needed an easy way to check the contents of multiple directories. From there, I compare the contents with a database that contains more information about the files.

Retrieving the contents of a directory in C# is very easy, and the code is included below.
DirectoryInfo directory = new DirectoryInfo("C:/some/directory");
FileInfo[] files = directory.GetFiles();
foreach (FileInfo onefile in files){
Console.WriteLine(onefile.Name);
}
The DirectoryInfo object points at a directory on the system. From here, the program has access to create and delete other directories, list directories and files, and view last accessed time information. GetFiles() returns an array of FileInfo objects, and from there, the program has access to information about each file in the directory.

No comments:

Post a Comment