Get drive name from drive letter using c#

To find drive or volume name if you already know the drive letter is very easy using c#. System.IO can be used to find the drive name using drive letter. VolumeLabel under the namespace System.IO can be used to get the volume name of a drive.
Find volume name using c#

Using c# find drive name

  1. Use the namespace System.IO
  2. Create object of type DriveInfo.
  3. Pass the drive letter as constructor parameter while creating object of DriveInfo.
  4. Use VolumeLabel to extract volume label of the drive.
Also read: Find drive name using C++

Code:

using System.IO;

DriveInfo driveVariable=new DriveInfo("C"); //C is the drive letter
string Name=driveVariable.VolumeLabel; // string Name is used to store the drive volume name

Example:

using System;
using System.IO;
namespace findVolumeName
{
    class Program
    {
        public string getVolumeName(string drive)
        {
            DriveInfo usbDrive = new DriveInfo(drive);
            string name = usbDrive.VolumeLabel;
            return name;
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            string driveName=obj.getVolumeName("C");
            Console.WriteLine(driveName);
        }
    }
}

Note*: The program displays names drives only if the drive has a name assigned. If no name was assigned then default name(Local Disk / USB Drive) is not displayed. User can use if condition to check the drive name is empty or null and can assign the default name.

Exceptions:
While using the VolumeLabel property, following exceptions can occur:

If there is a disk error or if the disk is not ready.

If the drive does not exist

If the calling program does not have the required permission.

The volume label may be in a different network


Comments