Enumerating, Managing and Monitoring File system using C#

Applications often need to read and write data to the disk, sometimes for the sake of user and most of the times for its internal use. To do this task we need to review the present file system of the disk and then manage the resources according to our requirements. In some applications, it is required to monitor any changes made to the file system and notify them accordingly.

Although there are number of articles written on the web about this topic, still I want to go with this topic in detailed for one more time. The main aim of this article is to understand the file system and manage it through some inbuilt C# classes. The article is written keeping beginners in mind.

Analyzing File System:

Understanding Drives Structure:

The following code gets the complete basic information about the file system drives. It uses DriveInfo.GetDrives method in System.IO namespace to retrieve a collection of DriveInfo objects. The important information about the drives is later retrieved using static properties of DriveInfo.

using System;
using System.Collections.Generic;                               
using System.Linq;
using System.Text;
using System.IO;
namespace FileSystem
{
    class DrivesStructure
    {
        public static void Main()
        {
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                Console.WriteLine("Drive Name : "+drive.Name);
                Console.WriteLine("Drive RootDirectory : " + drive.RootDirectory);
                Console.WriteLine("Drive type : " + drive.DriveType);
                Console.WriteLine("Drive Ready Or Not : " + drive.IsReady);
                if (drive.DriveType == DriveType.Fixed)
                {
                    Console.WriteLine("Drive Format : " + drive.DriveFormat);
                    Console.WriteLine("Drive total Size : " + drive.TotalSize);
                    Console.WriteLine("Drive Available free Space : " + drive.AvailableFreeSpace);
                    Console.WriteLine("Drive Total Free Space : " + drive.TotalFreeSpace);
                }
                Console.WriteLine();
            }                
        }
    }
}

 

Enumerating through Files and Folders:

DirectoryInfo class in .NET can be used to enumerate through files and folders of a specific location. The following code explains how to browse files and folders; it displays all the files and folders in C:\Program Files.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FileSystem { class BrowseFilesAndFolders { public static void Main() { string DirectoryPath = @"C:\Program Files"; DirectoryInfo DInfo = new DirectoryInfo(@DirectoryPath); foreach (DirectoryInfo d in DInfo.GetDirectories()) Console.WriteLine(d.FullName); foreach (FileInfo f in DInfo.GetFiles()) Console.WriteLine(f.Name); } } }

Managing Files and Folders:

To create a Folder (Directory structure) –

It’s always better to check whether the directory is already existed one using an instance of DirectoryInfo and its static Exists Method.

//using static Directory class
Directory.CreateDirectory(@"E:\Test");
Console.WriteLine("Directory Test Created");

//using DirectiryInfo instance
DirectoryInfo dir1 = new DirectoryInfo(@"E:\Test\Test1");
dir1.Create();
Console.WriteLine("Directory Test1 Created"); 

To create a File –

// using an instance of FileInfo Class
FileInfo fi = new FileInfo(@"E:\Test\ABC.txt");
fi.CreateText();
Console.WriteLine("File ABC is created");

Similarly use File.Copy, File.Move and File.Delete of Static File Class to perform the corresponding actions on a file. The same operations can also be achieved using an instance of FileInfo class and calling its CopyTo, MoveTo and Delete methods.

Monitoring File System:

The file system can be monitored using FileSystemWatcher class of System.IO namespace. Operation like updates on files, new files, renaming of files can be easily monitored using the former said class. The following code demonstrates the basic implementation of the FileSystemWatcher class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileSystem
{
    class FileSystemWatcherDemo
    {
        public static void Main(string [] args)
        {
            FileSystemWatcher fsw = new FileSystemWatcher();
            fsw.Path = @"E:\";
            fsw.IncludeSubdirectories = true;
            fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastAccess;
            fsw.Changed += new FileSystemEventHandler(fsw_Changed);
            fsw.Created += new FileSystemEventHandler(fsw_Changed);
            fsw.Deleted += new FileSystemEventHandler(fsw_Changed);
            fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
            fsw.EnableRaisingEvents = true;
            Console.ReadLine();
        }
        static void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.ChangeType + "-----" + e.FullPath);
        }
        static void fsw_Renamed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.ChangeType + "-----" + e.FullPath);
        }
    }
}

First an instance of FileSystemWatcher is created and then it is configured according to our requirements. Then an event handler is added to the corresponding changed events. There can be only one event handler for changed, created and deleted operations, but for renamed operation there should be a separate event handler. The process of creating event handlers and then wiring them to actual operations are clearly shown in code listed above. Finally, EnableRaisingEvents of FileSystemWatcher is set to true.

FileSystemWatcher can be configured with the properties like Filter (used to specify the file types to be monitored), NotifyFilter (used to specify the types of changes for which to throw events) and Path (used to specify the directory path to be monitored).

Note:

  1. All operations listed in this article need System.IO namespace imported.
  2. The above coding is done for console application in C#.

Conclusion:

The information about the drives of file system is analyzed using DriveInfo class. The practical use of DirectoryInfo and FileInfo classes in creating and enumerating of directories and files is observed. Also the use of static File and Directory class is observed and implemented. Finally file system is monitored for any changes using FileSystemWatcher class of System.IO namespace.

You may also like...