我正在运行WMI查询,但我需要一种方法来测试连接在运行任何查询之前是否正常工作。
以下是我在运行任何查询之前测试连接所创建的方法。
关于如何测试连接失败的任何想法?
private void btnQuery_Click(object sender, EventArgs e)
{
string strPC = txtPCName.Text.ToString();
string strDrive = txtDrive.Text.ToString();
if (strPC == "" || strDrive == "" || txtUser.Text.ToString() == "" || txtPW.Text.ToString() == "")
{
MessageBox.Show("The PC Name/ Drive Letter / Username / Or Password is blank. Please make sure all of these fields are filled out");
}
else
{
//Set up the connection first and test that it is working properly
ConnectionOptions connection = new ConnectionOptions();
connection.Username = txtUser.Text;
connection.Password = txtPW.Text;
connection.Authority = "ntlmdomain:expd";
ManagementScope mgmtScope = new ManagementScope("\\\\" + strPC + "\\root\\cimv2", connection);
if (pTestWMIConnection(mgmtScope) == true)
{
//Get PC Information
double dblMem = pGetMemUsage("FreePhysicalMemory", mgmtScope);
double dblTotDisk = pGetTotalDiskSpace(strDrive, mgmtScope);
double dblFreeDisk = pGetFreeDiskSpace(strDrive, mgmtScope);
txtMem.Text = Math.Round(dblMem, 2).ToString() + " MB";
txtDriveTot.Text = Math.Round(dblTotDisk, 2).ToString() + " GB";
txtFreeDisk.Text = Math.Round(dblFreeDisk, 2).ToString() + " GB";
txtSN.Text = pGetWMIInfo("Win32_BIOS", "SerialNumber", mgmtScope);
txtIP.Text = pGetIPAddress("Win32_NetworkAdapterConfiguration", "IPAddress", mgmtScope);
txtModel.Text = pGetWMIInfo("Win32_ComputerSystem", "Model", mgmtScope);
txtArch.Text = pGetWMIInfo("Win32_OperatingSystem", "OSArchitecture", mgmtScope);
SetBalloonTip("Complete", "PC Query Completed");
}
else
{
MessageBox.Show("Connection to remote PC failed");
}
}
}
public static bool pTestWMIConnection(ManagementScope mgmtScope)
{
try
{
mgmtScope.Connect();
if (mgmtScope.IsConnected == true)
{
return true;
}
}
catch (ManagementException err)
{
MessageBox.Show("Unable to Return some or all of the information requested - " + err.Message);
return false;
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
MessageBox.Show("Username or Password might be incorrect - " + unauthorizedErr.Message);
return false;
}
return false;
}
答案 0 :(得分:0)
如果你的程序在try catch语句中崩溃,那么看起来好像返回异常不是ManagementException
或System.UnauthorizedAccessException
尝试一下,只需使用Catch(Exception ex)
来捕获所有异常,然后通过错误输入信息来触发错误并查看它是什么错误类型,然后处理它。你的错误处理似乎已经足够了一个消息框,我认为正在将例程踢回用户修复输入并重新提交,所以我会模仿系统启动时出现的任何错误的相同功能。