[C# – I/O] Managing File Systems

Let’s start with files and folders(directories). It is very straight-forward and easy to do basic file management tasks in .NET. Just find the pattern and think of each section of this post as a how-to manual. Most types related I/O are under the “System.IO” namespace.

Usually 2 types are provided for each file system type (file, directory, …).  For example, the “Directory” class provides static methods and the “DirectoryInfo” class provides instance methods.

 

1. Enumerating Drives

Let’s start with drives. You might want to know how many drives are in your system and their types.

There’s only 1 type: “System.IO.DriveInfo“.

You can get the DriveInfo objects in 2 ways:

  • Get a list of drives using the static method “GetDrives()
  • Use the constructor with a drive name: new DriveInfo(“c”)

– Properties –

  • string Name { get; }: the name of a drive
  • string DriveFormat { get; }: the name of the file system on the specified drive
  • DriveType DriveType { get; }: the drive type ( “Unknown“, “NoRootDirectory“, “Removable“, “Fixed“, “Network“, “CDRom“, or “Ram“)
  • string VolumeLabel { get; set; }: the volume label of a drive.
  • bool IsReady { get; }: indicating whether a drive is ready (such as whether a CD is in a CD drive)
  • long TotalSize { get; }: the total size of storage space on a drive (in bytes)
  • long TotalFreeSpace { get; }: the total amount of free space available on a drive (in bytes)
  • long AvailableFreeSpace { get; }: the amount of available free space to the current user on a drive (in bytes)
  • DirectoryInfo RootDirectory { get; }: the root directory of a drive

Note that USB drives are “Removable” and DVDs are also “CDRom“.

privated static Dictionary<string, string> GetDriveInfo(DriveInfo drive)
{
  Dictionary<string, string> infos = new Dictionary<string, string>();
  infos.Add("DriveType", drive.DriveType.ToString());
  infos.Add("IsReady", drive.IsReady.ToString());
  if (drive.IsReady)
  {
    infos.Add("DriveFormat", drive.DriveFormat);
    infos.Add("TotalSize", drive.TotalSize.ToString("N0"));
    infos.Add("TotalFreeSpace", drive.TotalFreeSpace.ToString("N0"));
    infos.Add("AvailableFreeSpace", drive.AvailableFreeSpace.ToString("N0"));
  }
  return infos;
}

private static void PrintInfo(Dictionary<string, string> infos)
{
  foreach (KeyValuePair<string, string> info in infos)
  {
    Console.WriteLine($"{info.Key}: {info.Value}");
  }
}

public static void GetAllDrives()
{
  foreach (DriveInfo drive in DriveInfo.GetDrives())
  {
    Console.WriteLine($" ==== {drive.Name} ==== ");
    PrintInfo(GetDriveInfo(drive));
    Console.WriteLine();
  }
}

 

2. Managing Folders and Files

You can use the “System.IO.Directory” or “System.IO.DirectoryInfo” class to browse folders and files. For one-time task, you can use the static methods of the “Directory” class. If you want to perform multiple tasks, you need to create the “DirectoryInfo” object.

The “System.IO.File” or the “System.IO.FileInfo” classes are used to retrieve information of a single file.

 

3. Directory/File Information

Both “DirectoryInfo” and “FileInfo” classes are derived from the “System.IO.FileSystemInfo” class.

The “System.IO.FileSystemInfo” class provides the following properties:

  • string FullName { get; }: the full path of the directory or file
  • string Name { get; }:  the name of the directory or file
  • FileAttributes Attributes { get; set; }: the attributes for the current directory
  • string Extension { get; }: the string representing the extension part of the file
  • bool Exists { get; }: indicating whether the directory exists
  • DateTime CreationTime { get; set; }: the creation time
  • DateTime LastAccessTime { get; set; }: the time the current directory was last accessed
  • DateTime LastWriteTime { get; set; }: the time the current directory was last written to

The “DirectoryInfo” provides the following additional properties:

  • DirectoryInfo Parent { get; }: the parent directory of a specified subdirectory
  • DirectoryInfo Root { get; }: the root portion of a path

The “FileInfo” provides the following properties:

  • bool IsReadOnly { get; set; }: indicating whether the current file is read only
  • long Length { get; }: the size of the current file (in bytes)

 

4. Browsing Directories and Files

  • Create an instance of the “DirectoryInfo” class by specifying the folder

– Methods –

  • DirectoryInfo[] GetDirectories()
  • FileInfo[] GetFiles()

.NET 4 provides the following new methods:

  • IEnumerable<DirectoryInfo> EnumerateDirectories()
  • IEnumerable<FileInfo> EnumerateFiles()

These “Enumerate—()” methods provide more efficient way to browse folders and files because you can start enumerating the collection of DirectoryInfo/FileInfo objects before the whole collection is returned. When you use GetFiles, you must wait for the whole array of DirectoryInfo/FileInfo objects to be returned before you can access the array.

public static void BrowseFilesAndFolders(string folderToBrowse)
{
  DirectoryInfo rootDir = new DirectoryInfo(folderToBrowse);
  Console.WriteLine(" ==== {0} ==== ", rootDir.FullName);

  // files
  foreach (FileInfo file in rootDir.EnumerateFiles())
  {
    Console.WriteLine("t ===== {0} ==== ", file.FullName);
  }

  // sub folders
  foreach (DirectoryInfo dir in rootDir.EnumerateDirectories())
  {
    BrowseFilesAndFolders(dir.FullName);
  }
}
This entry was posted in C# and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s