2015-04-25 29 views
2

我正尝试从C#应用程序重命名计算机名称。使用.NET重命名计算机名称

public class ComputerSystem : IComputerSystem 
{ 
    private readonly ManagementObject computerSystemObject; 

    public ComputerSystem() 
    { 
     var computerPath = string.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName); 
     computerSystemObject = new ManagementObject(new ManagementPath(computerPath)); 
    } 

    public bool Rename(string newComputerName) 
    { 
     var result = false; 

     var renameParameters = computerSystemObject.GetMethodParameters("Rename"); 
     renameParameters["Name"] = newComputerName; 

     var output = computerSystemObject.InvokeMethod("Rename", renameParameters, null); 

     if (output != null) 
     { 
      var returnValue = (uint)Convert.ChangeType(output.Properties["ReturnValue"].Value, typeof(uint)); 
      result = returnValue == 0; 
     } 

     return result; 
    } 
} 

的WMI调用返回错误代码1355

MSDN没有过多提及的错误代码,这是什么意思,我该如何解决?

+0

是你特林在Active Directory环境中重新命名的电脑吗? –

+1

这个*可能会对你有些兴趣:https://social.msdn.microsoft.com/Forums/vstudio/en-US/219c4b4b-b43a-4dbc-9e3c-a1135879c5f9/information-about-the-domain- could not-be-retrieve-1355?forum = netfxbcl –

回答

3

Error code 1355表示ERROR_NO_SUCH_DOMAIN“指定的域不存在或无法联系。”

documentation for the Rename method指出名称必须包含域名的。对于未加入域的计算机,请尝试使用.\NewName而不是仅使用NewName

+0

感谢您的链接到系统错误!收藏它,这将有助于未来的日子。并感谢您解决我的问题(我正在域PC上测试,但该程序最终会在非域PC上运行,我会找出一些东西) – bas

0

由于保护系统,使用任何外部方法更新PC名称非常困难。最好的方法是使用Windows自己的WMIC.exe实用程序来重命名PC。只需从C#启动wmic.exe,并将rename命令作为参数传递即可。

退出代码0

>

public void SetMachineName(string newName) 
{ 

    // Create a new process 
    ProcessStartInfo process = new ProcessStartInfo(); 

    // set name of process to "WMIC.exe" 
    process.FileName = "WMIC.exe"; 

    // pass rename PC command as argument 
    process.Arguments = "computersystem where caption='" + System.Environment.MachineName + "' rename " + newName; 

    // Run the external process & wait for it to finish 
    using (Process proc = Process.Start(process)) 
    { 
     proc.WaitForExit(); 

     // print the status of command 
     Console.WriteLine("Exit code = " + proc.ExitCode); 
    } 
} 
+0

不要发布多个相同内容的答案。如果适用,请发布一个很好的答案并关闭其他答案。你已经在这里发布了http://stackoverflow.com/a/36107899/1743880 – Tunaki