【问题标题】:Read from an external text file in a built WPF application从构建的 WPF 应用程序中的外部文本文件中读取
【发布时间】:2020-07-12 10:17:48
【问题描述】:

我正在 WPF 中构建一个桌面应用程序,它需要来自外部文本文件的用户首选项。该文件应该可供用户在最终构建和发布后直接操作。

        String settingsPath = "settings.txt";
        try
        {
            if (!File.Exists(settingsPath)) 
                throw new Exception("settings file does not exist");

            String settingsText = File.ReadAllText(settingsPath);
            MessageBox.Show(settingsText);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            Window.GetWindow(this).Close();
        }

即使我使用文件资源管理器创建 settings.txt 文件,它也会在构建时引发异常。

【问题讨论】:

  • 抛出什么异常?

标签: c# wpf desktop-application


【解决方案1】:

您正在创建的文本文件可能不在工作目录文件夹中。 使用此代码诊断您的问题,它将显示您的代码在哪里寻找文件。

        String settingsPath = "settings.txt";
        try
        {
            if (!File.Exists(settingsPath))
                throw new FileNotFoundException("settings file does not exist", Path.GetFullPath(settingsPath));

            String settingsText = File.ReadAllText(settingsPath);
            MessageBox.Show(settingsText);
        }
        catch (FileNotFoundException fileEx)
        {
            MessageBox.Show($"{fileEx.Message}:{fileEx.FileName}");
            Window.GetWindow(this).Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            Window.GetWindow(this).Close();
        }

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2015-12-23
    相关资源
    最近更新 更多