gpt4 book ai didi

c# - 我如何放入异常捕获

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:59 25 4
gpt4 key购买 nike

我有下面的代码,它通过并返回磁盘信息。运行时,我注意到某些 WMI 属性在我的计算机上不可用(即 FirmwareRevision)。

因此,当我运行代码时,VS 崩溃并显示“未找到”。知道我是如何在未找到对象的输出中设置异常捕获以声明“不可用”的。

我一直在阅读有关异常捕获的内容,但到目前为止我的业余方法是明确定义我想使用的异常...该程序打算在不同服务器的负载上运行,因此希望它能够智能地找出 WMI 对象任何一台服务器都可能没有。

代码如下,目前它失败了(最后一行):

"lblFirmware.Text = "Firmware: " +moDisk["FirmwareRevision"].ToString();"

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using Microsoft.Win32;

namespace diskdrive_info
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//Get all the disk drives
ManagementObjectSearcher mosDisk = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
// Loop through each object (disk) retrieved by WMI
foreach (ManagementObject moDisk in mosDisk.Get())
{
cmbHdd.Items.Add(moDisk["Model"].ToString());
}
}

private void cmbHdd_SelectedIndexChanged(object sender,EventArgs e)
{
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
lblModel.Text = "Model: " + moDisk["Model"].ToString();
lblCapacity.Text = "Capacity: " + moDisk["Size"].ToString();
lblPartitions.Text = "Partitions: " + moDisk["Partitions"].ToString();
lblSectors.Text = "Sectors: " + moDisk["SectorsPerTrack"].ToString();
lblSignature.Text = "Signatures: " +moDisk["Signature"].ToString();
lblFirmware.Text = "Firmware: " +moDisk["FirmwareRevision"].ToString();
}
}


}
}

最佳答案

尝试替换:

lblFirmware.Text = "Firmware: " +moDisk["FirmwareRevision"].ToString();

与:

lblFirmware.Text = "Firmware: " + moDisk["FirmwareRevision"] == null ? "Not Available" :  moDisk["FirmwareRevision"].ToString();

关于c# - 我如何放入异常捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12532551/

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