Skip to content

.NET File System classes

by Alex Peck on July 22nd, 2009

In .NET it is extremely easy to manipulate the file system using the classes defined in System.IO. The classes which have the suffix Info provide functions to operate on an instance, and derive from FileSystemInfo. Other classes provide static methods, and when there are both info and non-info equivalents, may be more efficient when you only need to perform a single operation.

This list summarises the classes and enumerations pertinent to the framework foundation exam:

  • The Directory and DirectoryInfo classes provide methods for creating, renaming and deleting directories. Note: there is no copy method.
  • The DriveInfo class exposes information about a drive, such as free space or format. It does not inherit from FileSystemInfo (you can’t delete drives).
  • The DriveType enumeration represents the possible drive types (Removable, Fixed, CDRom etc).
  • The File and FileInfo classes provide methods for creating, copying, renaming and deleting files.
  • FileAccess enumerates the rights required when opening a file (Read, Write, ReadWrite).
  • FileMode enumerates the modes in which a file may be opened (Append, Create, CreateNew, Open, OpenOrCreate, Truncate).
  • The ErrorEventArgs is an EventArgs class with an additional method to retrieve the original error: GetException.
  • The Path class provides a series of static methods to manipulate paths, and retrieve properties, such as path or volume seperators, or characters considered invalid in a path.
  • The RenamedEventArgs class extends EventArgs by adding new properties for name and path before and after the rename took place.

Since niether Directory nor DirectoryInfo provide a copy method, here is my implementation:

public static void CopyDirectory(string Source, string Target)
{
    // append separator if it's missing
    if (Target[Target.Length - 1] != Path.DirectorySeparatorChar)
    {
        Target += Path.DirectorySeparatorChar;
    }
 
    if (!Directory.Exists(Target))
    {
        Directory.CreateDirectory(Target);
    }
 
    String[] Files = Directory.GetFileSystemEntries(Source);
 
    foreach (string Element in Files)
    {
        if (Directory.Exists(Element))
        {
            CopyDirectory(Element, Target + Path.GetFileName(Element));
        }
        else
        {
            File.Copy(Element, Target + Path.GetFileName(Element), true);
        }
    }
}

MSDN provides a directory size function, I’m not sure why these are not part of the framework.

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS