Claude Assistant 7934d00ffb 修复编译错误
- 修复内插字符串中的条件运算符语法错误
- 替换Environment.TickCount64为Environment.TickCount以兼容.NET Framework 4.8
- 确保所有字符串插值表达式使用正确的括号包围

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-20 15:42:26 +08:00

784 lines
34 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Environmental_testing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 设置窗体图标 - 使用嵌入资源
try
{
var stream = GetType().Assembly.GetManifestResourceStream("Environmental_testing.app.ico");
if (stream != null)
{
this.Icon = new Icon(stream);
}
}
catch
{
// 如果图标加载失败,使用默认图标
// this.Icon = SystemIcons.Application;
}
}
private void btnDetect_Click(object sender, EventArgs e)
{
Log("开始系统环境检测...");
btnDetect.Enabled = false;
System.Threading.Tasks.Task.Run(() =>
{
try
{
// 清空现有信息
ClearAllInfo();
// 检测进度设置
int totalSteps = 5;
int currentStep = 0;
// 1. 检测系统信息
this.Invoke(new Action(() => UpdateProgress(++currentStep, totalSteps, "检测操作系统信息...")));
var systemInfo = GetSystemInfo();
this.Invoke(new Action(() => txtSystemInfo.Text = systemInfo));
Log("系统信息检测完成");
// 2. 检测硬件信息
this.Invoke(new Action(() => UpdateProgress(++currentStep, totalSteps, "检测硬件配置信息...")));
var hardwareInfo = GetHardwareInfo();
this.Invoke(new Action(() => txtHardwareInfo.Text = hardwareInfo));
Log("硬件信息检测完成");
// 3. 检测网络信息
this.Invoke(new Action(() => UpdateProgress(++currentStep, totalSteps, "检测网络环境信息...")));
var networkInfo = GetNetworkInfo();
this.Invoke(new Action(() => txtNetworkInfo.Text = networkInfo));
Log("网络信息检测完成");
// 4. 检测软件环境
this.Invoke(new Action(() => UpdateProgress(++currentStep, totalSteps, "检测软件环境信息...")));
var softwareInfo = GetSoftwareInfo();
this.Invoke(new Action(() => txtSoftwareInfo.Text = softwareInfo));
Log("软件环境检测完成");
this.Invoke(new Action(() => UpdateProgress(++currentStep, totalSteps, "检测完成!")));
this.Invoke(new Action(() => Log("所有环境检测完成!")));
}
catch (Exception ex)
{
this.Invoke(new Action(() => Log($"检测过程中发生错误: {ex.Message}")));
}
finally
{
this.Invoke(new Action(() =>
{
btnDetect.Enabled = true;
progressBar.Value = 0;
}));
}
});
}
private void btnExport_Click(object sender, EventArgs e)
{
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
dialog.FileName = $"系统环境检测报告_{DateTime.Now:yyyyMMdd_HHmmss}.txt";
dialog.Title = "导出环境检测报告";
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
ExportReport(dialog.FileName);
Log($"报告已导出到: {dialog.FileName}");
MessageBox.Show("报告导出成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
Log($"导出报告失败: {ex.Message}");
MessageBox.Show($"导出报告失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearAllInfo();
txtLog.Clear();
progressBar.Value = 0;
Log("已清空所有信息");
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void ClearAllInfo()
{
txtSystemInfo.Clear();
txtHardwareInfo.Clear();
txtNetworkInfo.Clear();
txtSoftwareInfo.Clear();
}
private void UpdateProgress(int current, int total, string status)
{
progressBar.Value = (int)((double)current / total * 100);
Log(status);
}
private void Log(string msg)
{
txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {msg}\r\n");
txtLog.ScrollToCaret();
Application.DoEvents();
}
private string GetSystemInfo()
{
var sb = new StringBuilder();
try
{
// 操作系统基本信息
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 操作系统基本信息");
sb.AppendLine("═══════════════════════════════════════");
var os = Environment.OSVersion;
sb.AppendLine($"操作系统版本: {os}");
sb.AppendLine($"系统架构: {(Environment.Is64BitOperatingSystem ? "64" : "32")}");
sb.AppendLine($"计算机名: {Environment.MachineName}");
sb.AppendLine($"用户名: {Environment.UserName}");
sb.AppendLine($"域名: {Environment.UserDomainName}");
// 系统目录信息
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 系统目录信息");
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine($"系统目录: {Environment.SystemDirectory}");
sb.AppendLine($"Windows目录: {Environment.GetFolderPath(Environment.SpecialFolder.Windows)}");
sb.AppendLine($"程序文件目录: {Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)}");
sb.AppendLine($"临时文件夹: {Path.GetTempPath()}");
// 系统启动信息
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 系统启动信息");
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine($"系统启动时间: {GetSystemBootTime()}");
sb.AppendLine($"当前时间: {DateTime.Now}");
sb.AppendLine($"系统已运行: {GetSystemUptime()}");
// 注册表获取更多系统信息
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{
if (key != null)
{
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 详细系统信息");
sb.AppendLine("═══════════════════════════════════════");
var productName = key.GetValue("ProductName")?.ToString() ?? "未知";
var editionId = key.GetValue("EditionID")?.ToString() ?? "未知";
var version = key.GetValue("CurrentVersion")?.ToString() ?? "未知";
var build = key.GetValue("CurrentBuild")?.ToString() ?? "未知";
var buildLab = key.GetValue("BuildLabEx")?.ToString() ?? "未知";
sb.AppendLine($"产品名称: {productName}");
sb.AppendLine($"版本号: {version}");
sb.AppendLine($"版本ID: {editionId}");
sb.AppendLine($"构建号: {build}");
if (!string.IsNullOrEmpty(buildLab))
{
sb.AppendLine($"完整构建信息: {buildLab}");
}
}
}
}
catch (Exception ex)
{
sb.AppendLine($"获取详细系统信息失败: {ex.Message}");
}
}
catch (Exception ex)
{
sb.AppendLine($"系统信息检测失败: {ex.Message}");
}
return sb.ToString();
}
private string GetHardwareInfo()
{
var sb = new StringBuilder();
try
{
// CPU信息
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" CPU 信息");
sb.AppendLine("═══════════════════════════════════════");
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0"))
{
if (key != null)
{
var processorName = key.GetValue("ProcessorNameString")?.ToString() ?? "未知CPU";
var vendor = key.GetValue("VendorIdentifier")?.ToString() ?? "未知";
var mhz = key.GetValue("~MHz")?.ToString() ?? "未知";
sb.AppendLine($"处理器型号: {processorName}");
sb.AppendLine($"制造商: {vendor}");
sb.AppendLine($"主频: {mhz} MHz");
sb.AppendLine($"处理器核心数: {Environment.ProcessorCount}");
}
}
}
catch (Exception ex)
{
sb.AppendLine($"获取CPU信息失败: {ex.Message}");
sb.AppendLine($"处理器核心数: {Environment.ProcessorCount}");
}
// 内存信息
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 内存信息");
sb.AppendLine("═══════════════════════════════════════");
var gc = GC.GetTotalMemory(false);
sb.AppendLine($"当前内存使用: {gc / 1024 / 1024} MB");
sb.AppendLine($"系统工作集内存: {Environment.WorkingSet / 1024 / 1024} MB");
// 获取总物理内存
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0"))
{
// 这里可以通过其他方式获取内存信息
}
var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
sb.AppendLine($"总物理内存: {computerInfo.TotalPhysicalMemory / 1024 / 1024} MB");
sb.AppendLine($"可用物理内存: {computerInfo.AvailablePhysicalMemory / 1024 / 1024} MB");
sb.AppendLine($"总虚拟内存: {computerInfo.TotalVirtualMemory / 1024 / 1024} MB");
sb.AppendLine($"可用虚拟内存: {computerInfo.AvailableVirtualMemory / 1024 / 1024} MB");
}
catch (Exception ex)
{
sb.AppendLine($"获取详细内存信息失败: {ex.Message}");
}
// 磁盘信息
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 磁盘信息");
sb.AppendLine("═══════════════════════════════════════");
var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
if (drive.IsReady)
{
sb.AppendLine($"驱动器 {drive.Name}:");
sb.AppendLine($" 文件系统: {drive.DriveFormat}");
sb.AppendLine($" 卷标: {drive.VolumeLabel}");
sb.AppendLine($" 总容量: {drive.TotalSize / 1024 / 1024 / 1024} GB");
sb.AppendLine($" 可用空间: {drive.AvailableFreeSpace / 1024 / 1024 / 1024} GB");
sb.AppendLine($" 已用空间: {(drive.TotalSize - drive.AvailableFreeSpace) / 1024 / 1024 / 1024} GB");
sb.AppendLine();
}
}
// 显卡信息
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 显卡信息");
sb.AppendLine("═══════════════════════════════════════");
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"))
{
if (key != null)
{
var subKeyNames = key.GetSubKeyNames();
foreach (var subKeyName in subKeyNames)
{
using (var subKey = key.OpenSubKey(subKeyName))
{
var driverDesc = subKey?.GetValue("DriverDesc")?.ToString();
if (!string.IsNullOrEmpty(driverDesc))
{
sb.AppendLine($"显卡: {driverDesc}");
}
}
}
}
}
}
catch (Exception ex)
{
sb.AppendLine($"获取显卡信息失败: {ex.Message}");
}
}
catch (Exception ex)
{
sb.AppendLine($"硬件信息检测失败: {ex.Message}");
}
return sb.ToString();
}
private string GetNetworkInfo()
{
var sb = new StringBuilder();
try
{
// 网络接口信息
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 网络接口信息");
sb.AppendLine("═══════════════════════════════════════");
var adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in adapters)
{
if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
sb.AppendLine($"网络接口: {adapter.Name}");
sb.AppendLine($" 类型: {adapter.NetworkInterfaceType}");
sb.AppendLine($" 状态: {adapter.OperationalStatus}");
sb.AppendLine($" 描述: {adapter.Description}");
if (adapter.OperationalStatus == OperationalStatus.Up)
{
var ipProperties = adapter.GetIPProperties();
// IP地址信息
foreach (var unicastIp in ipProperties.UnicastAddresses)
{
if (unicastIp.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ||
unicastIp.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
sb.AppendLine($" IP地址: {unicastIp.Address}");
sb.AppendLine($" 子网掩码: {unicastIp.IPv4Mask}");
}
}
// 网关信息
foreach (var gateway in ipProperties.GatewayAddresses)
{
sb.AppendLine($" 网关: {gateway.Address}");
}
// DNS服务器信息
foreach (var dns in ipProperties.DnsAddresses)
{
sb.AppendLine($" DNS服务器: {dns}");
}
}
sb.AppendLine();
}
}
// 公网IP信息
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 公网连接信息");
sb.AppendLine("═══════════════════════════════════════");
try
{
// 检测网络连接状态
sb.AppendLine($"本地连接测试: {TestNetworkConnection()}");
// 获取公网IP需要网络连接
var publicIP = GetPublicIPAddress();
if (!string.IsNullOrEmpty(publicIP))
{
sb.AppendLine($"公网IP地址: {publicIP}");
}
else
{
sb.AppendLine("公网IP地址: 无法获取");
}
}
catch (Exception ex)
{
sb.AppendLine($"获取公网信息失败: {ex.Message}");
}
// 网络配置信息
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 网络配置信息");
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine($"主机名: {Dns.GetHostName()}");
try
{
var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
sb.AppendLine("主机IP地址:");
foreach (var ip in hostEntry.AddressList)
{
sb.AppendLine($" {ip}");
}
}
catch (Exception ex)
{
sb.AppendLine($"获取主机IP失败: {ex.Message}");
}
}
catch (Exception ex)
{
sb.AppendLine($"网络信息检测失败: {ex.Message}");
}
return sb.ToString();
}
private string GetSoftwareInfo()
{
var sb = new StringBuilder();
try
{
// .运行时环境
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" .NET运行时环境");
sb.AppendLine("═══════════════════════════════════════");
// .NET Framework版本
sb.AppendLine(".NET Framework版本:");
GetNetFrameworkVersions(sb);
// 当前应用运行环境
sb.AppendLine();
sb.AppendLine("当前运行时信息:");
sb.AppendLine($" .NET版本: {Environment.Version}");
sb.AppendLine($" CLR版本: {Environment.Version}");
// 浏览器信息
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 浏览器信息");
sb.AppendLine("═══════════════════════════════════════");
GetBrowserInfo(sb);
// 已安装软件(部分常用软件)
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 已安装软件信息");
sb.AppendLine("═══════════════════════════════════════");
GetInstalledSoftware(sb);
// 环境变量
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine(" 重要环境变量");
sb.AppendLine("═══════════════════════════════════════");
var envVars = new[]
{
"PATH", "TEMP", "TMP", "USERNAME", "COMPUTERNAME",
"OS", "PROCESSOR_ARCHITECTURE", "NUMBER_OF_PROCESSORS",
"WINDIR", "SYSTEMROOT", "PROGRAMFILES", "PROGRAMFILES(X86)",
"COMMONPROGRAMFILES", "APPDATA", "LOCALAPPDATA", "USERPROFILE"
};
foreach (var envVar in envVars)
{
var value = Environment.GetEnvironmentVariable(envVar);
sb.AppendLine($"{envVar}: {value}");
}
}
catch (Exception ex)
{
sb.AppendLine($"软件环境检测失败: {ex.Message}");
}
return sb.ToString();
}
private void GetNetFrameworkVersions(StringBuilder sb)
{
try
{
using (RegistryKey ndpKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
{
if (ndpKey != null)
{
foreach (string versionKeyName in ndpKey.GetSubKeyNames())
{
if (versionKeyName.StartsWith("v"))
{
RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
if (versionKey != null)
{
object name = versionKey.GetValue("Version");
object sp = versionKey.GetValue("SP");
object install = versionKey.GetValue("Install");
if (install != null && install.ToString() == "1")
{
var versionInfo = $" {versionKeyName}";
if (name != null)
{
versionInfo += $" - {name}";
}
if (sp != null)
{
versionInfo += $" SP{sp}";
}
sb.AppendLine(versionInfo);
}
// 检查客户端和完整版本
RegistryKey subKey = versionKey.OpenSubKey("Client");
if (subKey != null)
{
name = subKey.GetValue("Version");
if (name != null)
{
sb.AppendLine($" {versionKeyName} (Client): {name}");
}
}
subKey = versionKey.OpenSubKey("Full");
if (subKey != null)
{
name = subKey.GetValue("Version");
if (name != null)
{
sb.AppendLine($" {versionKeyName} (Full): {name}");
}
}
}
}
}
}
}
}
catch (Exception ex)
{
sb.AppendLine($"获取.NET Framework版本失败: {ex.Message}");
}
}
private void GetBrowserInfo(StringBuilder sb)
{
// 检测常用浏览器
var browsers = new[]
{
new { Name = "Google Chrome", Path = @"SOFTWARE\Google\Chrome" },
new { Name = "Mozilla Firefox", Path = @"SOFTWARE\Mozilla\Mozilla Firefox" },
new { Name = "Microsoft Edge", Path = @"SOFTWARE\Microsoft\Edge" },
new { Name = "Internet Explorer", Path = @"SOFTWARE\Microsoft\Internet Explorer" }
};
foreach (var browser in browsers)
{
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(browser.Path))
{
if (key != null)
{
var version = key.GetValue("Version")?.ToString();
if (!string.IsNullOrEmpty(version))
{
sb.AppendLine($"{browser.Name}: {version}");
}
else
{
// 尝试其他版本键
var pv = key.GetValue("pv")?.ToString();
if (!string.IsNullOrEmpty(pv))
{
sb.AppendLine($"{browser.Name}: {pv}");
}
}
}
}
}
catch
{
// 浏览器未安装或无法访问注册表
}
}
}
private void GetInstalledSoftware(StringBuilder sb)
{
try
{
// 从注册表获取已安装软件
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"))
{
if (key != null)
{
var softwareList = new List<string>();
foreach (string subKeyName in key.GetSubKeyNames())
{
using (RegistryKey subKey = key.OpenSubKey(subKeyName))
{
if (subKey != null)
{
var displayName = subKey.GetValue("DisplayName")?.ToString();
var displayVersion = subKey.GetValue("DisplayVersion")?.ToString();
var publisher = subKey.GetValue("Publisher")?.ToString();
if (!string.IsNullOrEmpty(displayName))
{
var software = displayName;
if (!string.IsNullOrEmpty(displayVersion))
{
software += $" ({displayVersion})";
}
if (!string.IsNullOrEmpty(publisher))
{
software += $" - {publisher}";
}
softwareList.Add(software);
}
}
}
}
// 显示前20个软件
foreach (var software in softwareList.Take(20))
{
sb.AppendLine(software);
}
if (softwareList.Count > 20)
{
sb.AppendLine($"... 还有 {softwareList.Count - 20} 个软件未显示");
}
}
}
}
catch (Exception ex)
{
sb.AppendLine($"获取已安装软件失败: {ex.Message}");
}
}
private string GetSystemBootTime()
{
try
{
// 通过系统启动时间计算
var uptime = TimeSpan.FromMilliseconds(Environment.TickCount);
var bootTime = DateTime.Now - uptime;
return bootTime.ToString("yyyy-MM-dd HH:mm:ss");
}
catch
{
return "无法获取";
}
}
private string GetSystemUptime()
{
try
{
var uptime = TimeSpan.FromMilliseconds(Environment.TickCount);
return $"{uptime.Days}天 {uptime.Hours}小时 {uptime.Minutes}分钟 {uptime.Seconds}秒";
}
catch
{
return "无法获取";
}
}
private string TestNetworkConnection()
{
try
{
using (var ping = new Ping())
{
var reply = ping.Send("www.baidu.com", 3000);
return reply.Status == IPStatus.Success ?
$"正常 (延迟: {reply.RoundtripTime}ms)" :
$"异常 ({reply.Status})";
}
}
catch
{
return "无法检测";
}
}
private string GetPublicIPAddress()
{
try
{
// 使用简单的HTTP请求获取公网IP
var client = new WebClient();
client.Headers.Add("User-Agent", "Environment Checker");
var ip = client.DownloadString("https://api.ipify.org?format=text");
return ip.Trim();
}
catch
{
try
{
var client = new WebClient();
var response = client.DownloadString("http://ipinfo.io/ip");
return response.Trim();
}
catch
{
return null;
}
}
}
private void ExportReport(string fileName)
{
var sb = new StringBuilder();
sb.AppendLine("系统环境检测报告");
sb.AppendLine("═══════════════════════════════════════");
sb.AppendLine($"生成时间: {DateTime.Now:yyyy年MM月dd日 HH:mm:ss}");
sb.AppendLine($"检测工具: 系统环境检测工具");
sb.AppendLine();
sb.AppendLine(GetSystemInfo());
sb.AppendLine();
sb.AppendLine(GetHardwareInfo());
sb.AppendLine();
sb.AppendLine(GetNetworkInfo());
sb.AppendLine();
sb.AppendLine(GetSoftwareInfo());
File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);
}
}
}