c# 类型为“System.Runtime.InteropServices.COMException”的未处理异常
本文关键字:COMException 未处理 异常 InteropServices Runtime 类型 System | 更新日期: 2023-09-27 18:37:28
我正在运行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;
}
如果您的程序在 try catch 语句中崩溃,则看起来好像返回异常不是类型 ManagementException
或 System.UnauthorizedAccessException
相反,尝试简单地使用应该捕获所有异常的Catch(Exception ex)
,然后通过错误键入信息来触发错误,看看它是什么错误类型,然后处理它。 使用消息框,您的错误处理似乎足够了,我认为是将例程踢回给用户以修复输入并重新提交,因此我会模仿相同的功能,无论系统踢出什么错误。