List all Files and Directories in a Directory
We can list all the files in a directory. If we come across a directory our program should again explore it and find files within that directory.
Code:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO ;
public class Class1
{
static int filecount, dircount ;
static void Main( string[] args )
{
string path = "D:\test" ;
DirectoryInfo d = new DirectoryInfo ( path ) ;
Check ( d ) ;
Console.WriteLine ( "Total Files :" + filecount ) ;
Console.WriteLine ( "Total Directories :" + dircount ) ;
}
public static void Check ( DirectoryInfo d )
{
FileSystemInfo[] f = d.GetFileSystemInfos() ;
foreach ( FileSystemInfo i in f )
{
if (i.GetType().ToString()== "System.IO.DirectoryInfo" )
{
dircount++ ;
DirectoryInfo d1=new DirectoryInfo ( i.FullName ) ;
Console.WriteLine ( i.FullName ) ;
Check ( d1 ) ;
}
else
{
Console.WriteLine ( i.Name ) ;
filecount++ ;
}
}
}
}
Just like the FileInfo class, we have a DirectoryInfo class. To the constructor of this DirectoryInfo class we passed the path our user gave us. Recursion is the key to this program. We call a check function which checks whether the name passed is of a directory or a file. If it’s a file we print the name but if it’s a directory we pass the path to the Check( ) function again . Here we’ve used an array of FileSystemInfo. By using the GetFileSystemInfos( ) we get all entries in the supplied path. We ran a for loop on the entries. We also kept a count on the Directories and Files to get the total files and directories.
Quote:
Output:
D:\test
D:\test\lucpp
CHAP3.DOC
CHAP2.DOC
CHAP1.DOC
CHAP4.DOC
CHAP6.DOC
CHAP7.DOC
CHAP8.DOC
CHAP10.DOC
CHAP11.DOC
CHAP12.DOC
CHAP13.DOC
CHAP5.DOC
BACKCVR.DOC
CHAP9.DOC
CPPBOOK.DOT
INTRO.DOC
TITLE.DOC
text1.txt
text2.txt
text3.txt
Total Files :20
Total Directories :1