C# 获取本地磁盘驱动器、U盘、共享目录所在驱动器的大小
string filePathRoot = Path.GetPathRoot(fileName); if (!filePathRoot.EndsWith("\\")) { filePathRoot = filePathRoot + "\\"; } DriveType driveType = (DriveType)GetDriveType(filePathRoot); if (driveType == DriveType.FixedDisk || driveType == DriveType.FloppyOrUsb) //本地磁盘驱动器或usb、软盘 { } else if(driveType == DriveType.NetDisk) //网络共享文件夹所在磁盘大小 { }
[DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern int GetDriveType(string driveinfo); private enum DriveType { NotExist = 1, FloppyOrUsb = 2, FixedDisk = 3, NetDisk = 4, CDRom = 5, RAMDisk = 6 }
using System.Diagnostics.CodeAnalysis;
using System.Security;
以上是判断那种驱动器类型
获取本地磁盘驱动器剩余空间:
/// /// 获取指定驱动器的剩余空间总大小(单位为B) /// /// 只需输入代表驱动器的字母即可 /// public static long GetHardDiskFreeSpace(string str_HardDiskName) { long freeSpace = new long(); if(!str_HardDiskName.EndsWith("\\")) { str_HardDiskName = str_HardDiskName + ":\\"; } System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); foreach (System.IO.DriveInfo drive in drives) { if (drive.Name == str_HardDiskName) { freeSpace = drive.TotalFreeSpace; } } return freeSpace; }
用法:GetHardDiskFreeSpace(filePathRoot);
获取网络驱动器剩余空间:
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity] [DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetDiskFreeSpaceEx ( string lpszPath, // Must name a folder, must end with '\'. ref long lpFreeBytesAvailable, ref long lpTotalNumberOfBytes, ref long lpTotalNumberOfFreeBytes );
用法:
long freeSpaceNetFolder = 0, dummy1 = 0, dummy2 = 0;
GetDiskFreeSpaceEx(filePathRoot, ref freeSpaceNetFolder, ref dummy1, ref dummy2);