Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

GetComputerName (kernel32)
 
.
Summary
Retrieves a NetBIOS or DNS name associated with the local computer.
Summary

C# Signature:

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,
   StringBuilder lpBuffer, ref uint lpnSize);
    [System.Runtime.InteropServices.DllImport("Kernel32")]
    static extern unsafe bool GetComputerName(byte* lpBuffer, long* nSize);

VB.Net Signature:

<DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function GetComputerNameEx(ByVal NameType As COMPUTER_NAME_FORMAT, ByVal lpBuffer As StringBuilder, ByRef lpnSize As UInt32) As Boolean
End Function
       or

    [System.Runtime.InteropServices.DllImport("Kernel32", CharSet=CharSet.Auto)]
    public static extern bool GetComputerName(StringBuilder buffer, ref uint size);    

User-Defined Types:

COMPUTER_NAME_FORMAT

VB.NET Signature

<DllImport("kernel32.dll", EntryPoint:="GetComputerNameW", SetLastError:=True)> _
Public Function GetComputerName(<MarshalAs(UnmanagedType.LPTSTR)>sb As System.Text.StringBuilder, _
     ByRef length As Integer) As <MarshalAs(UnmanagedType.Bool)>Boolean
End function    

Notes:

None.

VB Signature:

Declare Function GetComputerName Lib "kernel32" (ByVal lpBuffer As String, ByRef nMax As Integer) As Boolean

Tips & Tricks:

Please add some!

User-Defined Types:

None.

Sample Code:

Please add some!

Notes:

The GetComputerName function retrieves the NetBIOS name of the local computer. This name is established at system startup, when the system reads it from the registry.

C# Sample:

    class Class1
    {
    enum COMPUTER_NAME_FORMAT
    {
        ComputerNameNetBIOS,
        ComputerNameDnsHostname,
        ComputerNameDnsDomain,
        ComputerNameDnsFullyQualified,
        ComputerNamePhysicalNetBIOS,
        ComputerNamePhysicalDnsHostname,
        ComputerNamePhysicalDnsDomain,
        ComputerNamePhysicalDnsFullyQualified
    }

    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,
        StringBuilder lpBuffer, ref uint lpnSize);

Tips & Tricks:

    [STAThread]
    static void Main(string[] args)
    {
        bool success;
        StringBuilder name = new StringBuilder(260);
        uint size = 260;
        success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain, name, ref size);
        Console.WriteLine(name.ToString());
    }
     }

Powershell sample

    $signature = @"
      using System;
      using System.Text;
      using System.Runtime.InteropServices;
      namespace Test_Namespace{
    public enum COMPUTER_NAME_FORMAT
    {
        ComputerNameNetBIOS,
        ComputerNameDnsHostname,
        ComputerNameDnsDomain,
        ComputerNameDnsFullyQualified,
        ComputerNamePhysicalNetBIOS,
        ComputerNamePhysicalDnsHostname,
        ComputerNamePhysicalDnsDomain,
        ComputerNamePhysicalDnsFullyQualified
    }
    public class Test_class{
        [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
        public static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,
          StringBuilder lpBuffer, ref uint lpnSize);
    }      
    }    
    "@
    Add-Type -TypeDefinition $signature -PassThru
    $size = 64
    # way 2 to declare string builder
    $str_builder_obj = [System.Text.StringBuilder]::new($size)
    # run the method
    [Test_Namespace.Test_class]::GetComputerNameEx([Test_Namespace.COMPUTER_NAME_FORMAT]::ComputerNameDnsDomain, $str_builder_obj, [ref]$size)
    # view the contents
    $str_builder_obj.ToString()

Make sure to go in to the build properties of your project and check "Allow Unsafe Code". Second version doesn't require this.

Alternative Managed API:

Do you know one? Please contribute it!

Sample Code C#:

    using System.Management;
    using System.Runtime.InteropServices;

Documentation

    class Class1
        [System.Runtime.InteropServices.DllImport("Kernel32")>
            static extern unsafe bool GetComputerName(byte* lpBuffer, long* nSize);

        [STAThread]
        static void Main(string[] args)
        {
           byte[] buffor = new byte[512];
            long size = buffor.Length;
               unsafe
             {
            long* pSize = &size;
            fixed (byte* pBuffor = buffor)
            {
              GetComputerName(pBuffor, pSize);
            }
                }
           System.Text.Encoding textEnc = new System.Text.ASCIIEncoding();
           System.Console.WriteLine("Computer name: {0}", textEnc.GetString(buffor));         
        }
    }

Sample Code (VB.NET):

    Imports System.Management
    Imports System.Runtime.InteropServices

    Public Class Class1
         <DllImport("kernel32.dll", EntryPoint:="GetComputerNameW", SetLastError:=True)> _
         Public Function GetComputerName(<MarshalAs(UnmanagedType.LPTSTR)>sb As System.Text.StringBuilder, _
             ByRef length As Integer) As <MarshalAs(UnmanagedType.Bool)>Boolean
         End function

        <STAThread> _
        Public Sub Main()
           Dim buffer As System.Text.StringBuilder
           buffer = new System.Text.StringBuilder(512)
           Dim Size as Integer = buffer.Length

           GetComputerName(buffer, Size)
           System.Console.WriteLine(buffer.ToString()))
        End Sub
    End Class

Sample Code (VB):

Dim buff As String = Space(255)
Dim max As Integer = 255
Dim rc As Integer

rc = GetComputerName(buff,max)
' Now, max contains the total number of characters written to the buffer
MessageBox.Show( Mid(buff,1,max) )

Alternative Managed API:

System.Environment.MachineName will get you the netbios name.

Documentation

Sample Code (VB 2005):

Imports System.Runtime.InteropServices

Imports System.Text

<DllImport("Kernel32", CharSet:=CharSet.Unicode, EntryPoint:="GetComputerNameA", SetLastError:=True)> _

     Private Function GetCompName(ByVal Puffer As StringBuilder, ByRef Laenge As IntPtr) As Integer

End Function

Private Declare Function GetComputerNameAlt Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As StringBuilder, ByVal nSize As Integer) As Integer

    Declare Unicode Function GetCompName2 Lib "Kernel32" Alias "GetComputerNameA" (ByVal Puffer As StringBuilder, ByRef Laenge As IntPtr) As Integer

Sub Main()

    Dim CompName As New StringBuilder()
    Dim Ret As Integer
    'Ret = GetComputerNameAlt(CompName, 100)
    Ret = GetCompName2(CompName, 100)
    Dim CompNameBytes() As Byte = Encoding.Unicode.GetBytes(CompName.ToString)
    Dim CompNameStr As String = Encoding.Default.GetString(CompNameBytes)
    Console.WriteLine("Der Computer heißt: {0}", CompNameStr)
    Console.ReadLine()
    End Sub

Documentation
Visual Basic 2005 Kompendium

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions