欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#获取本地磁盘信息

程序员文章站 2022-05-14 08:32:14
直接上干货简单易懂 //磁盘监控(远程/本地) //需要引用System.Management.dll public class RemoteMonitoring { private static string strMsg = ""; private static long freesize = ......

直接上干货简单易懂

//磁盘监控(远程/本地)
//需要引用System.Management.dll
public class RemoteMonitoring
{
private static string strMsg = "";
private static long freesize = 0, size = 0;
private static long gb = 1024 * 1024 * 1024;//GB,这里可以自己定义获取是MB还是GB

public static string ThreadDisk()
{
strMsg = "";
string strHostName = Dns.GetHostName(); //取得本机的主机名
IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
string localip = ipEntry.AddressList[0].ToString(); //假设本地主机为单网卡,取得第一个IP
try
{
long minsize = long.Parse(CommonField.minsize);
if (CommonField.ip == localip)
{
#region 本机
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Fixed)
{
freesize = drive.TotalFreeSpace / gb;
size = drive.TotalSize / gb;
if (freesize <= minsize)
{
strMsg += localip + "磁盘" + drive.Name + "的可用空间为" + freesize + "GB,请及时清理!" + System.Environment.NewLine;
}
strMsg += "磁盘" + drive.Name + "的总空间:" + size + "MB!" + "可用空间:" + freesize + "GB!" + System.Environment.NewLine;
}
}
#endregion
}
return strMsg;
}
catch (Exception ex)
{
strMsg = ex.Message;
}
return strMsg;
}

}