C# Simplified, part 5: Error Handling and Files - Displaying all files under a directory
(Page 5 of 8 )
It is very easy to populate all files within a directory by using C#. All you need to do is create an instance of DirectoryInfo class and call the GetFiles() method. Since you are displaying all the files, you must use the foreach() loop. Listing 5.6 shows you how to display all jpeg files under a particular directory.
Listing 5.6
DirectoryInfo dir = new DirectoryInfo(@”F:\WINNT”);
FileInfo[] bmpfiles = dir.GetFiles(“*.bmp);
Console.WriteLine(“Total number of bmp files” , bmpfiles.Length);
Foreach( FileInfo f in bmpfiles)
{
Console.WriteLine(“Name is : {0}”, f.Name);
Console.WriteLine(“Length of the file is : {0}”, f.Length);
Console.WriteLine(“Creation time is : {0}”, f.CreationTime);
Console.WriteLine(“Attributes of the file are : {0}”, f.Attributes.ToString());
}
Creating Subdirectories
C# enables you to programmatically create a subdirectory with the help of the CreateSubDirectory() method. In listing 5.7, a subdirectory named MYSUB is created under SUB directory. The new directory will be created on the D drive of your system.
Listing 5.7
using System;
using System.IO;
class CreateDir
{
public static void Main()
{
DirectoryInfo dir = new DirectoryInfo(@"D:\");
try
{
dir.CreateSubdirectory("SUB");
dir.CreateSubdirectory(@"SUB\MYSUB");
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
}
After executing the above code, go to the D drive and verify the existence of the newly created directories.
Next: Creating files >>
More C# Articles
More By Anand Narayanaswamy