gpt4 book ai didi

c# - C#类型为 'System.Runtime.InteropServices.COMException'的未处理异常

转载 作者:行者123 更新时间:2023-12-03 08:53:00 25 4
gpt4 key购买 nike

我正在运行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语句中崩溃,则看起来好像返回异常不是ManagementExceptionSystem.UnauthorizedAccessException类型

相反,尝试使用Catch(Exception ex)捕获所有异常,然后通过错误输入信息来触发错误并查看错误类型,然后进行处理。您可以使用一个消息框来进行错误处理,并且我认为是将例程踢回用户以修复输入并重新提交,因此无论系统出现什么错误,我都将模仿相同的功能。

关于c# - C#类型为 'System.Runtime.InteropServices.COMException'的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com