欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 编程语言 > c# >内容正文

c#

c#得到硬盘信息 -凯发k8官方网

发布时间:2024/10/8 c# 0 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 c#得到硬盘信息 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

using system;
using system.runtime.interopservices;
using system.text;


namespace disck
{
    [serializable]
    public struct harddiskinfo
    {
        ///


        /// 型号厂商
        ///

        public string modulenumber;
        ///
        /// 固件版本
        ///

        public string firmware;
        ///
        /// 物理序列号
        ///

        public string serialnumber;
        ///
        /// 容量,以m为单位
        ///

        public uint capacity;
    }


    #region internal structs


    [structlayout(layoutkind.sequential, pack = 1)]
    internal struct getversionoutparams
    {
        public byte bversion;
        public byte brevision;
        public byte breserved;
        public byte bidedevicemap;
        public uint fcapabilities;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 4)]
        public uint[] dwreserved; // for future use.
    }


    [structlayout(layoutkind.sequential, pack = 1)]
    internal struct ideregs
    {
        public byte bfeaturesreg;
        public byte bsectorcountreg;
        public byte bsectornumberreg;
        public byte bcyllowreg;
        public byte bcylhighreg;
        public byte bdriveheadreg;
        public byte bcommandreg;
        public byte breserved;
    }


    [structlayout(layoutkind.sequential, pack = 1)]
    internal struct sendcmdinparams
    {
        public uint cbuffersize;
        public ideregs irdriveregs;
        public byte bdrivenumber;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 3)]
        public byte[] breserved;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 4)]
        public uint[] dwreserved;
        public byte bbuffer;
    }


    [structlayout(layoutkind.sequential, pack = 1)]
    internal struct driverstatus
    {
        public byte bdrivererror;
        public byte bidestatus;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 2)]
        public byte[] breserved;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 2)]
        public uint[] dwreserved;
    }


    [structlayout(layoutkind.sequential, pack = 1)]
    internal struct sendcmdoutparams
    {
        public uint cbuffersize;
        public driverstatus driverstatus;
        public idsector bbuffer;
    }


    [structlayout(layoutkind.sequential, pack = 1, size = 512)]
    internal struct idsector
    {
        public ushort wgenconfig;
        public ushort wnumcyls;
        public ushort wreserved;
        public ushort wnumheads;
        public ushort wbytespertrack;
        public ushort wbytespersector;
        public ushort wsectorspertrack;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 3)]
        public ushort[] wvendorunique;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 20)]
        public byte[] sserialnumber;
        public ushort wbuffertype;
        public ushort wbuffersize;
        public ushort weccsize;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 8)]
        public byte[] sfirmwarerev;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 40)]
        public byte[] smodelnumber;
        public ushort wmorevendorunique;
        public ushort wdoublewordio;
        public ushort wcapabilities;
        public ushort wreserved1;
        public ushort wpiotiming;
        public ushort wdmatiming;
        public ushort wbs;
        public ushort wnumcurrentcyls;
        public ushort wnumcurrentheads;
        public ushort wnumcurrentsectorspertrack;
        public uint ulcurrentsectorcapacity;
        public ushort wmultsectorstuff;
        public uint ultotaladdressablesectors;
        public ushort wsingleworddma;
        public ushort wmultiworddma;
        [marshalas(unmanagedtype.byvalarray, sizeconst = 128)]
        public byte[] breserved;
    }


    #endregion


    ///


    /// atapi驱动器相关
    ///

    public class atapidevice
    {


        #region dllimport


        [dllimport("kernel32.dll", setlasterror = true)]
        static extern int closehandle(intptr hobject);


        [dllimport("kernel32.dll", setlasterror = true)]
        static extern intptr createfile(
        string lpfilename,
        uint dwdesiredaccess,
        uint dwsharemode,
        intptr lpsecurityattributes,
        uint dwcreationdisposition,
        uint dwflagsandattributes,
        intptr htemplatefile);


        [dllimport("kernel32.dll")]
        static extern int deviceiocontrol(
        intptr hdevice,
        uint dwiocontrolcode,
        intptr lpinbuffer,
        uint ninbuffersize,
        ref getversionoutparams lpoutbuffer,
        uint noutbuffersize,
        ref uint lpbytesreturned,
        [out] intptr lpoverlapped);


        [dllimport("kernel32.dll")]
        static extern int deviceiocontrol(
        intptr hdevice,
        uint dwiocontrolcode,
        ref sendcmdinparams lpinbuffer,
        uint ninbuffersize,
        ref sendcmdoutparams lpoutbuffer,
        uint noutbuffersize,
        ref uint lpbytesreturned,
        [out] intptr lpoverlapped);


        const uint dfp_get_version = 0x00074080;
        const uint dfp_send_drive_command = 0x0007c084;
        const uint dfp_receive_drive_data = 0x0007c088;


        const uint generic_read = 0x80000000;
        const uint generic_write = 0x40000000;
        const uint file_share_read = 0x00000001;
        const uint file_share_write = 0x00000002;
        const uint create_new = 1;
        const uint open_existing = 3;


        #endregion


        #region gethddinfo


        ///


        /// 获得硬盘信息
        ///

        ///
        /// 硬盘序号byte temp = new byte(); temp = 0x0;
        ///参数根据你的硬盘的数量定   0表示第一个硬盘  
        ///
        /// 硬盘信息
        ///
        /// 参考lu0的文章:http://lu0s1.3322.org/app/2k1103.html
        /// by sunmast for everyone
        /// thanks lu0 for his great works
        /// 在windows 98/me中,s.m.a.r.t并不缺省安装,请将smartvsd.vxd拷贝到%system%\iosubsys目录下。
        /// 在windows 2000/2003下,需要administrators组的权限。
        ///

        ///
        /// atapidevice.gethddinfo()
        ///

        public static harddiskinfo gethddinfo(byte driveindex)
        {
            switch (environment.osversion.platform)
            {
                case platformid.win32windows:
                    return gethddinfo9x(driveindex);
                case platformid.win32nt:
                    return gethddinfont(driveindex);
                case platformid.win32s:
                    throw new notsupportedexception("win32s is not supported.");
                case platformid.wince:
                    throw new notsupportedexception("wince is not supported.");
                default:
                    throw new notsupportedexception("unknown platform.");
            }
        }


        #region gethddinfo9x


        private static harddiskinfo gethddinfo9x(byte driveindex)
        {
            getversionoutparams vers = new getversionoutparams();
            sendcmdinparams inparam = new sendcmdinparams();
            sendcmdoutparams outparam = new sendcmdoutparams();
            uint bytesreturned = 0;


            intptr hdevice = createfile(
            @"\\.\smartvsd",
            0,
            0,
            intptr.zero,
            create_new,
            0,
            intptr.zero);
            if (hdevice == intptr.zero)
            {
                throw new exception("open smartvsd.vxd failed.");
            }
            if (0 == deviceiocontrol(
            hdevice,
            dfp_get_version,
            intptr.zero,
            0,
            ref vers,
            (uint)marshal.sizeof(vers),
            ref bytesreturned,
            intptr.zero))
            {
                closehandle(hdevice);
                throw new exception("deviceiocontrol failed:dfp_get_version");
            }
            // if ide identify command not supported, fails
            if (0 == (vers.fcapabilities & 1))
            {
                closehandle(hdevice);
                throw new exception("error: ide identify command not supported.");
            }
            if (0 != (driveindex & 1))
            {
                inparam.irdriveregs.bdriveheadreg = 0xb0;
            }
            else
            {
                inparam.irdriveregs.bdriveheadreg = 0xa0;
            }
            if (0 != (vers.fcapabilities & (16 >> driveindex)))
            {
                // we don''t detect a atapi device.
                closehandle(hdevice);
                throw new exception(string.format("drive {0} is a atapi device, we don''t detect it", driveindex 1));
            }
            else
            {
                inparam.irdriveregs.bcommandreg = 0xec;
            }
            inparam.bdrivenumber = driveindex;
            inparam.irdriveregs.bsectorcountreg = 1;
            inparam.irdriveregs.bsectornumberreg = 1;
            inparam.cbuffersize = 512;
            if (0 == deviceiocontrol(
            hdevice,
            dfp_receive_drive_data,
            ref inparam,
            (uint)marshal.sizeof(inparam),
            ref outparam,
            (uint)marshal.sizeof(outparam),
            ref bytesreturned,
            intptr.zero))
            {
                closehandle(hdevice);
                throw new exception("deviceiocontrol failed: dfp_receive_drive_data");
            }
            closehandle(hdevice);


            return getharddiskinfo(outparam.bbuffer);
        }


        #endregion


        #region gethddinfont


        private static harddiskinfo gethddinfont(byte driveindex)
        {
            getversionoutparams vers = new getversionoutparams();
            sendcmdinparams inparam = new sendcmdinparams();
            sendcmdoutparams outparam = new sendcmdoutparams();
            uint bytesreturned = 0;


            // we start in nt/win2000
            intptr hdevice = createfile(
            string.format(@"\\.\physicaldrive{0}", driveindex),
            generic_read | generic_write,
            file_share_read | file_share_write,
            intptr.zero,
            open_existing,
            0,
            intptr.zero);
            if (hdevice == intptr.zero)
            {
                throw new exception("createfile faild.");
            }
            if (0 == deviceiocontrol(
            hdevice,
            dfp_get_version,
            intptr.zero,
            0,
            ref vers,
            (uint)marshal.sizeof(vers),
            ref bytesreturned,
            intptr.zero))
            {
                closehandle(hdevice);
                throw new exception(string.format("drive {0} may not exists.", driveindex 1));
            }
            // if ide identify command not supported, fails
            if (0 == (vers.fcapabilities & 1))
            {
                closehandle(hdevice);
                throw new exception("error: ide identify command not supported.");
            }
            // identify the ide drives
            if (0 != (driveindex & 1))
            {
                inparam.irdriveregs.bdriveheadreg = 0xb0;
            }
            else
            {
                inparam.irdriveregs.bdriveheadreg = 0xa0;
            }
            if (0 != (vers.fcapabilities & (16 >> driveindex)))
            {
                // we don''t detect a atapi device.
                closehandle(hdevice);
                throw new exception(string.format("drive {0} is a atapi device, we don''t detect it.", driveindex 1));
            }
            else
            {
                inparam.irdriveregs.bcommandreg = 0xec;
            }
            inparam.bdrivenumber = driveindex;
            inparam.irdriveregs.bsectorcountreg = 1;
            inparam.irdriveregs.bsectornumberreg = 1;
            inparam.cbuffersize = 512;


            if (0 == deviceiocontrol(
            hdevice,
            dfp_receive_drive_data,
            ref inparam,
            (uint)marshal.sizeof(inparam),
            ref outparam,
            (uint)marshal.sizeof(outparam),
            ref bytesreturned,
            intptr.zero))
            {
                closehandle(hdevice);
                throw new exception("deviceiocontrol failed: dfp_receive_drive_data");
            }
            closehandle(hdevice);


            return getharddiskinfo(outparam.bbuffer);
        }


        #endregion


        private static harddiskinfo getharddiskinfo(idsector phdinfo)
        {
            harddiskinfo hddinfo = new harddiskinfo();


            changebyteorder(phdinfo.smodelnumber);
            hddinfo.modulenumber = encoding.ascii.getstring(phdinfo.smodelnumber).trim();


            changebyteorder(phdinfo.sfirmwarerev);
            hddinfo.firmware = encoding.ascii.getstring(phdinfo.sfirmwarerev).trim();


            changebyteorder(phdinfo.sserialnumber);
            hddinfo.serialnumber = encoding.ascii.getstring(phdinfo.sserialnumber).trim();


            hddinfo.capacity = phdinfo.ultotaladdressablesectors / 2 / 1024;


            return hddinfo;
        }


        private static void changebyteorder(byte[] chararray)
        {
            byte temp;
            for (int i = 0; i < chararray.length; i = 2)
            {
                temp = chararray[i];
                chararray[i] = chararray[i 1];
                chararray[i 1] = temp;
            }
        }


        #endregion
    }
}

转载于:https://www.cnblogs.com/hanwater/archive/2009/06/09/1499755.html

总结

以上是凯发k8官方网为你收集整理的c#得到硬盘信息的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

网站地图