© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
64 replies
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;
            }
        }
    }
}
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
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"
  }
}
{
  "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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

File writing
C#CC# / help
3y ago
✅ StreamWriter not writing to file
C#CC# / help
11mo ago
✅ StreamWriter not writing to file
C#CC# / help
2y ago
✅ Opening a Json file
C#CC# / help
12mo ago