C# .NET5 单文件应用程序从目录中读取和解析 Json/Txt 或其他文件格式 [英] C# .NET5 Single File Application Read and Parse Json / Txt or other file formats from directory

查看:48
本文介绍了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.

这篇关于C# .NET5 单文件应用程序从目录中读取和解析 Json/Txt 或其他文件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆