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

问题描述:

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

I am reading files on .NET Framework like this:

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

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

When I switch to .NET5 this only works on Debug mode. When I create a Single File Executable using Publish it is not running. When U click the Exe it never open or throws an exception. Also, try-catch block couldn't handle the exception.

发布设置:

如何在 .NET5 单个 Exe 文件上实现此功能?

How can I make this work on .NET5 Single Exe files?

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

You have to use Directory.GetCurrentDirectory() instead of 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 将其解析到您的班级.这也适用于 txt 或其他文件格式.

If you are reading a JSON file then, you can parse it to your class with Newtonsoft. This works for txt or other file formats too.