C# 从内置WPF应用程序中的外部文本文件读取
我正在WPF中构建一个桌面应用程序,它需要来自外部文本文件的用户首选项。最终构建和发布后,用户应可以直接操作该文件C# 从内置WPF应用程序中的外部文本文件读取,c#,wpf,desktop-application,C#,Wpf,Desktop Application,我正在WPF中构建一个桌面应用程序,它需要来自外部文本文件的用户首选项。最终构建和发布后,用户应可以直接操作该文件 String settingsPath = "settings.txt"; try { if (!File.Exists(settingsPath)) throw new Exception("settings file does not exis
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();
}
它会抛出什么异常?