Модераторы: Partizan, gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Как добавить Dll в проект, Dll для получения сис. инфы 
:(
    Опции темы
Barabeo
Дата 27.4.2011, 20:13 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



Нужно эту Dll подключить к моему проекту, т.е. чтобы всю эту инфу она вывела мне TextBox.
Вот код библиотеки
Код

using System;
using System.Collections;
using System.Net;
using System.Management;
using System.Diagnostics;
using System.Threading;

namespace MooseNet
{
    /// <summary>
    /// Utility class for methods that retrieve information about the system's current
    /// network configuration.  All methods are static.
    /// </summary>
    public class NetworkConfiguration
    {
        /// <summary>
        /// Obtains a list of all the IPAddresses currently assigned to this machine.  The
        /// loopback address is not included.
        /// </summary>
        /// <returns>An ArrayList of IPAddress objects</returns>
        public static ArrayList GetIPAddressList()
        {
            ArrayList ips = new ArrayList();

            try
            {
                IPAddress[] addrs = Dns.Resolve(Dns.GetHostName()).AddressList;
                for ( int i = 0; i < addrs.Length; i++ )
                {
                    if ( !IPAddress.IsLoopback(addrs[i]) )
                        ips.Add( addrs[i] );
                }
            }
            catch ( Exception )
            {
            }

            return ips;
        }

        /// <summary>
        /// Obtains the fully qualified domain name of the local machine
        /// </summary>
        /// <returns>The FQDN of the local machine.</returns>
        public static string GetLocalHostName()
        {
            return Dns.GetHostName();
        }

        /// <summary>
        /// Returns the domain name for the local machine
        /// </summary>
        /// <returns>The domain name of the local machine.</returns>
        public static string GetLocalDomainName()
        {
            IPHelperAPI.FIXED_INFO finfo = new IPHelperAPI.FIXED_INFO();

            if ( IPHelperAPI.GetNetworkParams( ref finfo ) != IPHelperAPI.NO_ERROR )
                return "";

            return finfo.domainName;
        }

        /// <summary>
        /// Retrieves an ArrayList of IPAddress which represent all of the known DNS servers.
        /// This method makes use of the internally held cache of AdapterTCPIPSettings in order
        /// to save processing time.
        /// </summary>
        /// <returns>Returns an ArrayList of IPAddresses</returns>
        public static ArrayList GetDNSServers()
        {
            Monitor.Enter( _threadLock );
            try
            {
                if ( _settings == null )
                    RefreshTCPIPSettingCache();

                ArrayList results = new ArrayList();
                foreach( AdapterTCPIPSettings s in _settings )
                {
                    if ( s._dnsServers != null )
                    {
                        foreach ( IPAddress ip in s._dnsServers )
                        {
                            results.Add( ip );
                        }
                    }
                }

                return results;
            }
            finally
            {
                Monitor.Exit( _threadLock );
            }
        }

        /// <summary>
        /// Forces the internally held cache of AdapterTCPIPSettings to be updated
        /// </summary>
        public static void RefreshTCPIPSettingCache()
        {
            Monitor.Enter( _threadLock );
            try
            {
                _settings = GetTCPIPSettings();
            }
            finally
            {
                Monitor.Exit( _threadLock );
            }
        }

        /// <summary>
        /// Represents the current TCPIP settings of an adapter
        /// </summary>
        public class AdapterTCPIPSettings
        {
            /// <summary>
            /// The description of the adapter
            /// </summary>
            public string _description = null;
            /// <summary>
            /// The id for the adapter's settings
            /// </summary>
            public string _id = null;
            /// <summary>
            /// The MAC address of the adapter
            /// </summary>
            public string _macAddress = null;
            /// <summary>
            /// Whether or not the adapters IP information is DHCP assigned
            /// </summary>
            public bool _dhcp = false;
            /// <summary>
            /// An array of IP Addresses in string format
            /// </summary>
            public IPAddress[] _ips = null;
            /// <summary>
            /// An array of subnet masks in string format
            /// </summary>
            public IPAddress[] _subnets = null;
            /// <summary>
            /// An array of default gateways in string format
            /// </summary>
            public IPAddress[] _gateways = null;
            /// <summary>
            /// An array of DNS servers in string format
            /// </summary>
            public IPAddress[] _dnsServers = null;
            /// <summary>
            /// The DNS domain assigned to this adapter
            /// </summary>
            public string _dnsDomain = null;
            /// <summary>
            /// The DNS suffix search order
            /// </summary>
            public string[] _dnsDomainSuffixSearchOrder = null;
        }

        /// <summary>
        /// Retrieves an ArrayList of AdapterTCPIPSettings.  This can take quite a while to
        /// get live data so call it rather infrequently.
        /// </summary>
        /// <returns>Returns and ArrayList of AdapterTCPIPSettings</returns>
        public static ArrayList GetTCPIPSettings()
        {
            ArrayList results = new ArrayList();

            try
            {
                results = GetTCPIPSettings_WMI();
                return results;
            }
            catch ( Exception ex )
            {
                Trace.WriteLine( "WMI failed: " + ex.Message );
            }

            results = GetTCPIPSettings_IPHLPAPI();
            return results;
        }

        private static ArrayList GetTCPIPSettings_WMI()
        {
            ArrayList results = new ArrayList();

            // Weed out all the Adapter Configurations first
            SelectQuery query = new SelectQuery( "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = true" );
            ManagementObjectSearcher searcher = new ManagementObjectSearcher( query );
            foreach (ManagementObject row in searcher.Get()) 
            {

                // Now find all the related Adapters and make sure they are ok
                string objectPath = "Win32_NetworkAdapterConfiguration.Index=" + row["Index"].ToString();
        
                RelatedObjectQuery relateQuery = new RelatedObjectQuery( objectPath, "Win32_NetworkAdapter", "Win32_NetworkAdapterSetting", "", "", "", "", false );
                ManagementObjectSearcher searcherRelate = new ManagementObjectSearcher( relateQuery );
                foreach ( ManagementObject rowR in searcherRelate.Get() )
                {
                    object cmec = rowR["ConfigManagerErrorCode"];

                    // Make sure CM says its working properly
                    if ( ( cmec != null ) && ( cmec.ToString() == "0" ) )
                    {
                        AdapterTCPIPSettings settings = new AdapterTCPIPSettings();

                        settings._description = (string)row["Description"];
                        settings._id = (string)row["SettingID"];
                        settings._macAddress = (string)row["MACAddress"];
                        settings._dhcp = (bool)row["DHCPEnabled"];
                        settings._ips = ConvertStringArrayToIPAddressArray( (string[])row["IPAddress"] );
                        settings._subnets = ConvertStringArrayToIPAddressArray( (string[])row["IPSubnet"] );
                        settings._gateways = ConvertStringArrayToIPAddressArray( (string[])row["DefaultIPGateway"] );
                        settings._dnsServers = ConvertStringArrayToIPAddressArray( (string[])row["DNSServerSearchOrder"] );
                        settings._dnsDomain = (string)row["DNSDomain"];
                        settings._dnsDomainSuffixSearchOrder = (string[])row["DNSDomainSuffixSearchOrder"];

                        results.Add( settings );
                    }
                }
            }

            return results;
        }

        private static ArrayList GetTCPIPSettings_IPHLPAPI()
        {
            ArrayList results = new ArrayList();
            ArrayList iphlpResults = new ArrayList();

            IPHelperAPI.FIXED_INFO finfo = new IPHelperAPI.FIXED_INFO();

            if ( IPHelperAPI.GetNetworkParams( ref finfo ) != IPHelperAPI.NO_ERROR )
                return results;

            if ( IPHelperAPI.GetAdaptersInfo( ref iphlpResults ) != IPHelperAPI.NO_ERROR )
                return results;
    
            foreach ( IPHelperAPI.IP_ADAPTER_INFO info in iphlpResults )
            {
                AdapterTCPIPSettings s = new AdapterTCPIPSettings();

                s._description = info.description;
                s._id = info.adapterName;
                s._dhcp = info.dhcpEnabled;
                s._dnsDomain = finfo.domainName;
                s._dnsDomainSuffixSearchOrder = null;
                s._dnsServers = ConvertIPArrayListToIPAddressArray( finfo.dnsServers );
                s._gateways = ConvertIPArrayListToIPAddressArray( info.gatewayList );
                s._ips = ConvertIPArrayListToIPAddressArray( info.ipAddressList );
                s._macAddress = ConvertMACAddressBytesToString( info.address );
                s._subnets = null;

                results.Add( s );
            }

            return results;
        }


        private static IPAddress[] ConvertStringArrayToIPAddressArray( string[] a )
        {
            if ( a == null )
                return null;

            IPAddress[] aip = new IPAddress[ a.Length ];
            int ndex = 0;
            foreach ( string s in a )
            {
                IPAddress addr = IPAddress.Parse( s );
                aip[ndex++] = addr;
            }

            return aip;
        }

        private static IPAddress[] ConvertIPArrayListToIPAddressArray( ArrayList a )
        {
            if ( a.Count == 0 )
                return null;

            IPAddress[] aip = new IPAddress[a.Count];
            int ndex = 0;
            foreach( IPAddress addr in a )
            {
                aip[ndex++] = addr;
            }

            return aip;
        }

        private static string ConvertMACAddressBytesToString( byte[] ab )
        {
            if ( ab.Length != 6 )
                return null;

            return string.Format( "{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", 
                ab[0], ab[1], ab[2], ab[3], ab[4], ab[5] );
        }

        private static ArrayList _settings = null;
        private static Int32 _threadLock = new Int32();
    }
}

PM MAIL   Вверх
jonie
Дата 27.4.2011, 22:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 5613
Регистрация: 21.8.2005
Где: Владимир

Репутация: 6
Всего: 118



скомпилировать. И добавить в Reference-ы (либо в студии, либо указав ключ /reference компилятора), и затем использовать в коде собственно. Вы что прочитали про C# ?


--------------------
Что-то не поняли? -> Напейтесь до зеленых человечков... эта сверхцивилизация Вам поможет...
PM MAIL Jabber   Вверх
Barabeo
Дата 28.4.2011, 09:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



Всё спасибо, разобрался.
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
Partizan
PashaPash

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, Partizan, PashaPash.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | .NET для новичков | Следующая тема »


 




[ Время генерации скрипта: 0.0674 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.