1

I am reading files on .NET Framework like this:

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

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.

Publish settings: publish settings

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

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
  • 4
    *this fails* - please always be more descriptive when asking other programmers for help. Exact error messages please – Caius Jard Apr 15 '21 at 05:51
  • Hi @CaiusJard I added more description and added publish settings ss. There is no error message, that's the main problem. – fatihyildizhan Apr 17 '21 at 05:33

2 Answers2

2

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

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.

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
0

If you are targetting settings.json file which resides along with your exe location. Then you can simply use

using Newtonsoft.Json;

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

Another methord is to use ExpressSettings NugGet.

It's a very simple library I created to read and write settings in .NET. You can read and write settings in one line of code.

It's available for .NET Framework and .NET Core. If you think it's usefull you can use here : https://github.com/sangeethnandakumar/Express-Settings

Sangeeth Nandakumar
  • 1,362
  • 1
  • 12
  • 23