【发布时间】:2011-11-30 14:13:40
【问题描述】:
我需要通过 .net 应用程序重命名我的计算机。 我试过这段代码:
public static bool SetMachineName(string newName)
{
MessageBox.Show(String.Format("Setting Machine Name to '{0}'...", newName));
// Invoke WMI to populate the machine name
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath(String.Format("Win32_ComputerSystem.Name='{0}'",System.Environment.MachineName))))
{
ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
inputArgs["Name"] = newName;
// Set the name
ManagementBaseObject outParams = wmiObject.InvokeMethod("Rename",inputArgs,null);
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if (ret == 0)
{
//worked
return true;
}
else
{
//didn't work
return false;
}
}
}
但是没有用。
我试过这个:
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern bool SetComputerName(string lpComputerName);
public static bool SetMachineName(string newName)
{
bool done = SetComputerName(newName);
if (done)
{
{ MessageBox.Show("Done"); return true; }
}
else
{ MessageBox.Show("Failed"); return false; }
}
但它也没有工作。
【问题讨论】:
-
“没有工作”的意思是....错误?
-
是否必须重新启动计算机才能真正反映更改?还是您遇到了一些错误?
-
@Olia 如果可能的话,通过第三方应用程序更改计算机名称会导致很多问题。
-
代码以第二种方式正常工作,没有例外,但重新启动后名称不会改变....在第一种方式中,ret值是!= 0,我得到错误 - -> 没用...
-
当我以第二种方式重命名计算机名称时,它不会改变 MyComuter 的属性,但是当我在 .net 中获取计算机名称时,我会看到新名称(更改名称.. .),怎么可能?