C#C
C#2y ago
Mek

✅ Writing a dictionary to json file

public Dictionary<string, string> CheckForStyleFile(string username)
{
    StyleModel defaultStyle = new()
    {
        BackgroundColor = "#000000",
        BorderColor = "#24de45",
        FontColor = "#CDCDCD"
    };

    Dictionary<string, string> defaultDict = new();
    defaultDict.Add("background", defaultStyle.BackgroundColor);
    defaultDict.Add("border", defaultStyle.BorderColor);
    defaultDict.Add("font", defaultStyle.FontColor);

    try
    {
        if (!File.Exists(_stylesFile))
        {
            var data = JsonSerializer.Serialize(defaultDict);
            File.AppendAllText(_stylesFile, data);
            return defaultDict;
        }
        else
        {
            if (username.Length == 0)
            {
                return defaultDict;
            }
        }
    }
}
I'm writing a helper function that is executed at run-time to check if the styles.json file exists and if it doesn't then it creates the file and writes in the default style dictionary. The wanted end result looks like this
{
  "default": {
      "background": "#000000",
      "border": "#42fe45",
      "font": "#CDCDCD"
  }
}
I've looked at a couple of different stack overflows, but they have some weird code as their solutions that I've never seen before.
Was this page helpful?