C# .NET5 单文件应用程序读取和解析 Json / Txt 或目录中的其他文件格式

C# .NET5 Single File Application Read and Parse Json / Txt or other file formats from directory

我正在像这样阅读 .NET Framework 上的文件:

string path = AppDomain.CurrentDomain.BaseDirectory + @"sources\settings.json";
string jsonResult = File.ReadAllText(path);
return JsonConvert.DeserializeObject<Settings>(jsonResult);

当我切换到 .NET5 时,这仅适用于调试模式。当我使用 Publish 创建 Single File Executable 时,它不是 运行。当您单击 Exe 时,它​​永远不会打开或引发异常。此外,try-catch 块无法处理异常。

发布设置:

如何在 .NET5 单个 Exe 文件上进行这项工作?

您必须使用 Directory.GetCurrentDirectory() 而不是 AppDomain.CurrentDomain.BaseDirectory

using Newtonsoft.Json;

public static Settings LoadSettingsFile()
{
  string currentPath = Directory.GetCurrentDirectory();
  string directoryPath = @$"{currentPath}\sources";
  string path = @$"{directoryPath}\settings.json";

  string jsonResult = File.ReadAllText(path);
  return JsonConvert.DeserializeObject<Settings>(jsonResult);
}

如果您当时正在读取 JSON 文件,您可以使用 Newtonsoft 将其解析为 class。这也适用于 txt 或其他文件格式。

如果您的目标是 settings.json 与您的 exe 位置一起驻留的文件。然后你可以简单地使用

using Newtonsoft.Json;

public static Settings ReadConfig()
{
  string path = @$"settings.json";
  string settingsText = File.ReadAllText(path);
  return JsonConvert.DeserializeObject<Settings>(settingsText);
}

另一种方法是使用 ExpressSettings NugGet。

这是我创建的一个非常简单的库,用于在 .NET 中读取和写入设置。 一行代码即可读写设置

它可用于 .NET Framework 和 .NET Core。 如果你认为它有用,你可以在这里使用:https://github.com/sangeethnandakumar/Express-Settings