我是靠谱客的博主 跳跃棒棒糖,最近开发中收集的这篇文章主要介绍C#获取驱动器盘符,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

 一、使用ManagementObjectSearcher类


static void Main(string[] args)
{
SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
foreach (ManagementObject disk in searcher.Get())
{
//获取驱动器盘符
Console.WriteLine(disk["Name"].ToString());
//卷标
Console.WriteLine(disk["VolumeName"].ToString());
//驱动器类型
string DriveType = disk["DriveType"].ToString();
switch (DriveType)
{
case "0":
Console.WriteLine("未知设备");
break;
case "1":
Console.WriteLine("未分区");
break;
case "2":
Console.WriteLine("可移动磁盘");
break;
case "3":
Console.WriteLine("硬盘");
break;
case "4":
Console.WriteLine("网络驱动器");
break;
case "5":
Console.WriteLine("光驱");
break;
case "6":
Console.WriteLine("内存磁盘");
break;
}
//容量
Console.WriteLine(GetSizeUseUnit(disk["Size"].ToString()));
//剩余空间
Console.WriteLine(GetSizeUseUnit(disk["FreeSpace"].ToString()));
}
}
public static string GetSizeUseUnit(string size)
{
double dSpace = Convert.ToDouble(size);
string sSpace = dSpace.ToString("N");
string[] tmp;
string rtnSize = "0";
tmp = sSpace.Split(',');
switch (tmp.GetUpperBound(0))
{
case 0:
rtnSize = tmp[0] + " 字节";
break;
case 1:
rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " K";
break;
case 2:
rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " M";
break;
case 3:
rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " G";
break;
case 4:
rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " T";
break;
}
return rtnSize;
}

二、使用DriveInfo类


static void Main(string[] args)
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine("
File type: {0}", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine("
Volume label: {0}", d.VolumeLabel);
Console.WriteLine("
File system: {0}", d.DriveFormat);
Console.WriteLine(
"
Available space to current user:{0, 15} bytes",
d.AvailableFreeSpace);
Console.WriteLine(
"
Total available space:
{0, 15} bytes",
d.TotalFreeSpace);
Console.WriteLine(
"
Total size of drive:
{0, 15} bytes ",
d.TotalSize);
}
}
}

三、使用Environment类,调用kernel32API获取驱动类型


[DllImport("kernel32")]
public static extern uint GetDriveType(string lpRootPathName);
static void Main(string[] args)
{
string[] drives = Environment.GetLogicalDrives();
foreach (string drive in drives)
{
//Determine icon to display by drive
switch (GetDriveType(drive))
{
case 2:
Console.WriteLine("软盘");
break;
case 3:
Console.WriteLine("硬盘");
break;
case 4:
Console.WriteLine("网络驱动器");
break;
case 5:
Console.WriteLine("光驱驱动器");
break;
default:
Console.WriteLine("");
break;
}
}
}




 

最后

以上就是跳跃棒棒糖为你收集整理的C#获取驱动器盘符的全部内容,希望文章能够帮你解决C#获取驱动器盘符所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部