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);

 

posted on   wu.g.q  阅读(312)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示