C#程式設計實現獲取當前計算機的名字
阿新 • • 發佈:2019-01-27
利用windows系統自帶的kernel32.dll檔案,然後將其引入到自己的專案中來,就可以輕鬆實現獲取計算機全名了,好了直接上程式碼
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Name { class Program { enum COMPUTER_NAME_FORMAT { ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified } [DllImport("kernel32.dll")] static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType, StringBuilder lpBuffer, ref uint lpnSize); static void Main(string[] args) { bool success; StringBuilder name = new StringBuilder(100); uint size = 100; success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsFullyQualified, name, ref size); Console.WriteLine(name.ToString()); } } }
需要注意的是函式在呼叫時注意引數的型別一定要一致