26.8.09

Classes for files and folders in C#

The .NET Framework provides a comprehensive set of base classes to explore the entire file system, finding out files and folders that are present and listing their properties (and a whole lot of them). These base classes expose methods that allow file and folder operations as well, such as moving, copying, deleting and renaming. Here we go through the available classes.

  1. FileInfo and DirectoryInfo

  2. These are non-static classes in the System.IO namespace that allow you to get almost any kind of information about files and folders and also allow operations like Deleting, Creating, Copying, Moving, etc. They are located in the System.IO namespace. Their constructors take a string that specifies the full path of the directory or file concerned.

    1. DirectoryInfo main = new DirectoryInfo(@"C:\hello");
    2. FileInfo main = new FileInfo(@"C:\hello.txt");



    If the file or directory does not actually exist, an exception is not thrown - just the Exists property is set to false. Once the instance is set, one can read as well as write properties like LastAccessTime, LastWriteTime, CreationTime and Attributes. The methods of DirectoryInfo class are more for the purpose of browsing through the file system while FileInfo instances are more often used to open streams to the file in question. This may be the reason why DirectoryInfo lacks the Length property of FileInfo which returns the size in bytes. One can write a tiny extension method for a DirectoryInfo instance:

    1. public static long GetSize(this DirectoryInfo dir)
    2. {
    3. long length = 0;
    4. foreach (FileInfo nextfile in dir.GetFiles())
    5. length += nextfile.Exists ? nextfile.Length : 0;
    6. foreach (DirectoryInfo nextdir in dir.GetDirectories())
    7. length += nextdir.Exists ? nextdir.GetSize() : 0;
    8. return length;
    9. }

    Although these classes can be used to move and copy files and folders, they are less preferable than the FileSystem class which we'll discuss later in this post.

  3. DriveInfo

  4. This class allows you to access any information about any drive in the machine. It is also located in the System.IO namespace. It provides a crucial single static method called GetDrives() which returns all the drives in the machine as an array of DriveInfo instances. Each of the DriveInfo instances can then be used to obtain drive information in properties like AvailableFreeSpace, TotalFreeSpace, DriveFormat, DriveType, Name, TotalSize and VolumeLabel. Perhaps the most important of these is the DriveType property which is an enum that provides for as many as 7 drive types viz. CDRom, Fixed, Removable, Network, NoRootDirectory, Ram and Unknown.
    Here's a sample method to get names of all removable drives:

    1. public static IEnumerable<string> GetRemovableDrives()
    2. {
    3. return from p in DriveInfo.GetDrives()
    4. where p.DriveType == DriveType.Removable & p.IsReady == true
    5. select p.Name;
    6. }

  5. FileSystem class

  6. This class allows you to move and copy files and folders. Though this can also be achieved with the DirectoryInfo and FileInfo classes as well, the difference is that FileSystem class hands over the transfer to the OS, so the OS provides the standard progress bar UI and the application can proceed normally. With the Info classes, the application is responsible for the transfer and so does not proceed to the next instruction until the transfer is complete, resulting in undesirable UI latency especially if the file or folder involved is large.

    1. FileSystem.MoveDirectory(@"C:\hello", @"D:\hello", UIOption.AllDialogs);
    2. FileSystem.CopyDirectory(@"C:\hello", @"D:\hello", UIOption.AllDialogs);
    3. FileSystem.MoveFile(@"C:\hello.txt", @"D:\hello.txt", UIOption.AllDialogs);
    4. FileSystem.CopyFile(@"C:\hello.txt", @"D:\hello.txt", UIOption.AllDialogs);

    It is located in a completely disparate Microsoft.VisualBasic.FileIO namespace.
    Other than just transferring files and folders, the FileSystem class provides in fact a wide range of static methods that emulate the behavior of other classes like FileStream, FileInfo and DirectoryInfo. A quick view and you'll know what I mean.

So, I suppose I covered all the .NET classes for Directories and Files. I hope it is useful to you!

2 comments:

  1. Very nicely written and explained ...

    Particularly the 'why FileSystem and not DirectoryInfo/FileInfo' case was an eye-opener.

    A question : While using 'FileSystem', do we have to add the requiste namespace 'As a reference' to our project before specifying the namespace in code-behind ... ?

    ReplyDelete
  2. Yes, you do! You need to add the .NET assembly Microsoft.VisualBasic as a project reference explicitly to use the namespace.

    ReplyDelete