C# Getting Information about your Drives

by CameronM 11. July 2010 17:56

Many moons ago I wrote a series of posts on how to access the file system from your Access database using Scripting.FileSystemObject in VBA. Just for fun and partly as a learning experience, I thought it was time to look at how the same can be achieved in .NET and more specifically C#.

This first post I wrote covered how to get information about the drives currently available on the host system. Here’s the VBA to .NET comparison.

VBA: Scripting.FileSystemObject.Drives = .NET: System.IO.DriveInfo.GetDrives()

To get started, open Visual Studio 2010 and create a new Console Application. In the Program.cs file add a using statement for the System.IO namespace, which contains all of the methods you’ll need to access drives, directories and files.

Code Snippet
  1. using System.IO;

Now insert the following code in the Main method. This code will get an array of DriveInfo objects, which contain the basic information of all the drives available on your system.

Code Snippet
  1. // get a list of drives available on the system
  2. DriveInfo[] drives = DriveInfo.GetDrives();
  3.  
  4. foreach (DriveInfo drive in drives)
  5. {
  6.     Console.WriteLine(drive.Name);
  7. }

Some interesting properties of the DriveInfo object are Name, AvailableFreeSpace and DriveForm (FAT/NTFC).

Tags:

C#