在构建的 WPF 应用程序中读取外部文本文件

Read from an external text file in a built WPF application

我正在 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 文件,它也会在构建时抛出异常。

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

        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();
        }