现在的位置: 首页 > 综合 > 正文

C# 获取USB磁盘信息

2013年11月01日 ⁄ 综合 ⁄ 共 1500字 ⁄ 字号 评论关闭

USB设备插入USB接口之后,windows产生设备消息,发往每一个window消息队列,可以从WndProc中获得USB插入或移除消息:

protected override void  WndProc(ref Message sysm)
        {
            const int WM_DEVICECHANGE = 0x219;
            const int DBT_DEVICEARRIVAL = 0x8000;
             try
            {
                if(sysm.Msg==WM_DEVICECHANGE)
                    if (sysm.WParam.ToInt32() == DBT_DEVICEARRIVAL)
                    {
                        string[] dirs = Environment.GetLogicalDrives(); //取得所有的盘符
                        foreach (string dir in dirs)
                        {
                            DriveInfo Tdriver=new DriveInfo(dir);
                            if(Tdriver.DriveType==DriveType.Removable){
                            {
                                while (Tdriver.IsReady == false) {
                                    Thread.Sleep(500);
                                }
                                try
                                {
                                    string PSTR = "";
                                    PSTR += "磁盘名称:" + Tdriver.Name + "\r\n";
                                    PSTR += "磁盘卷标:" + Tdriver.VolumeLabel + "\r\n";
                                    PSTR += "文件系统:" + Tdriver.DriveFormat + "\r\n";
                                    PSTR += "剩余大小:" + Tdriver.AvailableFreeSpace.ToString() + "\r\n";
                                    PSTR += "总体容量:" + Tdriver.TotalSize.ToString() + "\r\n";
                                    MessageBox.Show(PSTR);
                                }
                                catch {
                                    MessageBox.Show("error");
                                }
 
                            }
                        }
 
                    }
 
                }
 
            }
            catch
            { }
            base.WndProc(ref    sysm);

通过对dirs的的检测,可以发现哪些是USB盘,用USBPhysic.dll可以读取到USB设备的物理信息:

[DllImport("USBPhysic")]
  public static extern int Init(string sUser, string sRegCode);
 
[DllImport("USBPhysic")]
  public static extern int GetUSBPhysicInfo(int diskIndex, int InfoType, StringBuilder pHddInfo);

以上是引用USBPhysic.dll中的两个方法,当然Init方法用来注册USBPhysic.dll,之后可以读取到设备信息:

private void Form1_Load(object sender, EventArgs e)
        {
            string Pstr = "";
            StringBuilder T = new StringBuilder();
            int A = Init("Mndsoft.com", "C88C-7F7A-725B");
            Pstr += "磁盘总数:" + A.ToString() + "\r\n";
            A = GetUSBPhysicInfo(0, 0, T);
            Pstr += "磁盘串号:" + T.ToString() + "\r\n";
            A = GetUSBPhysicInfo(0, 1, T);
            Pstr += "磁盘名称:" + T.ToString() + "\r\n";
            A = GetUSBPhysicInfo(0, 2, T);
            Pstr += "磁盘厂商:" + T.ToString() + "\r\n";
            MessageBox.Show(Pstr);
        }

上面默认读取0号磁盘信息,对于一个示例U盘,返回如下:

 

抱歉!评论已关闭.