-1

I am using the below code to programmatically change PC Name,

[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetComputerNameEx(COMPUTER_NAME_FORMAT nameType, [MarshalAs(UnmanagedType.LPTStr)] string lpBuffer);
private enum COMPUTER_NAME_FORMAT : int
{
   ComputerNameNetBIOS,
   ComputerNameDnsHostname,
   ComputerNameDnsDomain,
   ComputerNameDnsFullyQualified,
   ComputerNamePhysicalNetBIOS,
   ComputerNamePhysicalDnsHostname,
   ComputerNamePhysicalDnsDomain,
   ComputerNamePhysicalDnsFullyQualified,
   ComputerNameMax
}  

SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsHostname,"NEWName"); //Call this to change pc name

However, this only works if the application is running as administrator.

is there any other way to make this work without running the application as administrator?

I found this topic but it's not working on me.

Community
  • 1
  • 1
bernzkie
  • 1,269
  • 2
  • 16
  • 35
  • 1
    Allowing the modification of the PC name to admins only kinda makes sense from a security's perspective to me. – cadaniluk Sep 24 '16 at 11:47

2 Answers2

2

You need administrator privileges to run this function:

SetComputerNameEx can set the Computer Name (the first label of the full DNS name) or the primary DNS suffix of the local computer. It cannot set a fully qualified DNS name in one call. If the local computer is a node in a cluster, SetComputerNameEx sets NetBIOS or DNS name of the local computer, not that of the cluster virtual server. The process that calls the SetComputerNameEx function must have administrator privileges on the local computer. To compile an application that uses this function, define _WIN32_WINNT as 0x0500 or later. For more information, see Using the Windows Headers.

source (MSDN)

Jevgeni Geurtsen
  • 3,133
  • 4
  • 17
  • 35
0

To rename a PC requires elevated privileges, the same goes for modifying the registry. There's no way around that and its for a good reason, security.

mbrdev
  • 584
  • 5
  • 9