You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF电阻计算器Try/Catch未触发异常,路径错误无提示求助

问题分析与解决方案

为什么路径错误时未触发异常?

File.AppendAllText仅在实际尝试写入文件时才会抛出异常,部分无效路径场景可能不会立即触发(比如路径仅含空格、或系统可自动忽略的非法字符)。更可靠的方式是提前验证路径有效性,而非依赖写入时的异常捕获。

修复方案

我们需要实现:

  • 提前验证路径格式与目录存在性
  • 捕获异常后允许用户修正路径并重试写入
  • 优化日志写入逻辑,避免依赖UI控件值

修改后的代码

namespace ResistanceCalculator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            txtLogPath.Text = @"C:\Users\MyUser\Documents\Log file.txt";
        }

        private void txtVoltage_MouseDoubleClick(object sender, MouseButtonEventArgs e) => txtVoltage.Clear();
        private void txtCurrent_MouseDoubleClick(object sender, MouseButtonEventArgs e) => txtCurrent.Clear();
        private void txtLogPath_MouseDoubleClick(object sender, MouseButtonEventArgs e) => txtLogPath.Clear();

        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            if (!double.TryParse(txtVoltage.Text, out double voltageValue) || 
                !double.TryParse(txtCurrent.Text, out double currentValue))
            {
                MessageBox.Show("错误:请仅输入数字。");
                return;
            }

            double resistance = voltageValue / currentValue;
            lblAnswer.Content = resistance.ToString("F2"); // 保留两位小数提升可读性

            bool logSaved = false;
            while (!logSaved)
            {
                try
                {
                    string logPath = txtLogPath.Text.Trim();
                    if (string.IsNullOrWhiteSpace(logPath))
                    {
                        MessageBox.Show("错误:日志路径不能为空。");
                        txtLogPath.Focus();
                        continue;
                    }

                    // 解析完整路径并验证格式
                    string fullPath = Path.GetFullPath(logPath);
                    // 检查目录是否存在,不存在则自动创建(可选,若不需要可移除)
                    string directory = Path.GetDirectoryName(fullPath);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    // 用计算后的变量生成日志,避免依赖UI控件值
                    string logLine = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}, {voltageValue}, {currentValue}, {resistance}";
                    File.AppendAllText(fullPath, logLine + Environment.NewLine);
                    logSaved = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"错误:{ex.Message}\n请修正日志路径后重试。");
                    txtLogPath.Focus();
                }
            }
        }
    }
}

关键改进点

  • 提前路径验证:用Path.GetFullPath解析路径,自动处理相对路径/格式问题;可选自动创建缺失目录
  • 循环重试机制:捕获异常后提示用户修正路径,直到日志成功写入
  • 逻辑优化:日志内容直接使用计算后的变量,避免UI值被意外修改;日期和电阻值采用格式化输出
  • 代码简化:用箭头函数简化双击清空逻辑,变量名符合C#命名规范

内容的提问来源于stack exchange,提问作者Uuno Purhaturo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:35:29