.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Tuesday, December 27, 2005

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);

}

0 comments: