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.
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:
Using c# find drive name
- Use the namespace System.IO
- Create object of type DriveInfo.
- Pass the drive letter as constructor parameter while creating object of DriveInfo.
- Use VolumeLabel to extract volume label of the drive.
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);
}
}
}
Exceptions:
While using the VolumeLabel property, following exceptions can occur:
Comments
Post a Comment