Settings
Programs should remember how the user likes them. This lesson stores settings in a JSON file with defaults, handles a damaged file, and shows where programs keep such files.
What you will learn#
- the special folders of the user,
- defaults, loading and saving settings,
- a Ring class that hides the details,
- what to do when the file is missing or damaged.
Where do settings live?#
The system has a folder for every kind of file; .NET finds them with Environment.GetFolderPath:
| Name | For |
|---|---|
MyDocuments | files the user creates |
ApplicationData | settings that follow the user to other computers |
LocalApplicationData | settings and caches of this computer |
Desktop | the desktop |
A program normally keeps its settings in a file inside its own folder under ApplicationData, for example …\ApplicationData\MyProgram\settings.json. The tutorial uses the temp folder so that it leaves nothing behind.
The design#
| Rule | Why |
|---|---|
| every setting has a default | the first run, and a missing key, work |
| the file is JSON, readable by people | users and support can read and edit it |
| loading never fails the program | a damaged file must not stop the application |
| saving happens when the user changes something | a crash does not lose the choices |
The program#
# settings - defaults, a JSON file, loading, saving, and special folders
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Text.Json"
}
func main
# Where do programs keep their files? .NET knows the special folders of the user.
oEnvironment = new Environment()
? "Special folders exist:"
for cFolder in ["MyDocuments","ApplicationData","LocalApplicationData","Desktop"]
? " " + cFolder + " : " + (len(oEnvironment.GetFolderPath(cFolder)) > 0)
next
# For this tutorial the file is in the temp folder
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_settings-settings.json"])
if new File().Exists(cFile)
new File().Delete(cFile)
ok
# 1. The first run: there is no file, so the settings have their default values
oSettings = new Settings(cFile)
? nl + "First run"
showSettings(oSettings)
# 2. The user changes some settings, the program saves them
oSettings.setValue("name","Ann")
oSettings.setValue("fontSize",14)
oSettings.setValue("darkMode",1)
oSettings.save()
? nl + "The file now contains: " + new File().ReadAllText(cFile)
# 3. The next run: a new Settings object reads the file again
oAgain = new Settings(cFile)
? nl + "Second run"
showSettings(oAgain)
# 4. A file that is damaged must not stop the program: use the defaults
new File().WriteAllText([ :path = cFile, :contents = "this is not json {" ])
oBroken = new Settings(cFile)
? nl + "A damaged file: the defaults are used, error was: " + (len(oBroken.cLoadError) > 0)
showSettings(oBroken)
new File().Delete(cFile)
func showSettings oSettings
? " name = " + oSettings.getValue("name")
? " fontSize = " + oSettings.getValue("fontSize")
? " darkMode = " + oSettings.getValue("darkMode")
# A class for settings: a list of [key, value], defaults, loading and saving
class Settings
aValues = []
cFile = ""
cLoadError = ""
func init cPath
cFile = cPath
# the defaults: the keys that exist, and what they are before the user changes them
aValues = [["name","Guest"],["fontSize",11],["darkMode",0]]
readFile()
func getValue cKey
for aPair in aValues
if aPair[1] = cKey
return aPair[2]
ok
next
return ""
func setValue cKey, xValue
for nIndex = 1 to len(aValues)
if aValues[nIndex][1] = cKey
aValues[nIndex][2] = xValue
ok
next
# the file holds a JSON object: {"name":"Ann","fontSize":14,"darkMode":1}
func save
cJson = "{"
for nIndex = 1 to len(aValues)
if nIndex > 1
cJson += ","
ok
xValue = aValues[nIndex][2]
if isstring(xValue)
xValue = '"' + xValue + '"'
ok
cJson += '"' + aValues[nIndex][1] + '":' + xValue
next
cJson += "}"
new File().WriteAllText([ :path = cFile, :contents = cJson ])
# read the file and replace the defaults with the values that it has
func readFile
cLoadError = ""
if not new File().Exists(cFile)
return
ok
try
oDocument = new JsonDocument().Parse(new File().ReadAllText(cFile))
oRoot = oDocument.RootElement
for nIndex = 1 to len(aValues)
aFound = oRoot.TryGetProperty(aValues[nIndex][1]) # [found, element]
if aFound[1]
if isstring(aValues[nIndex][2])
aValues[nIndex][2] = aFound[2].GetString()
else
aValues[nIndex][2] = aFound[2].GetInt32()
ok
ok
next
oDocument.Dispose()
catch
cLoadError = cCatchError
doneSpecial folders exist:
MyDocuments : 1
ApplicationData : 1
LocalApplicationData : 1
Desktop : 1
First run
name = Guest
fontSize = 11
darkMode = 0
The file now contains: {"name":"Ann","fontSize":14,"darkMode":1}
Second run
name = Ann
fontSize = 14
darkMode = 1
A damaged file: the defaults are used, error was: 1
name = Guest
fontSize = 11
darkMode = 0How it works#
A class for settings#
Everything about settings is in one Ring class, Settings, so the rest of the program only says oSettings.getValue("name") and oSettings.setValue("fontSize",14). The class keeps a list of [key, value] pairs: its starting content is the list of defaults, so the keys that exist are defined in one place.
Saving#
save writes a JSON object by hand: texts in quotes, numbers without. For real data with arbitrary text use JsonSerializer (the tutorial JSON and XML), which also escapes quotes and line breaks.
Loading#
readFile first checks that the file exists. Then, inside try, it parses the JSON and, for every known key, asks TryGetProperty(key), which returns [found, element]: if found, the value replaces the default, read as a text (GetString) or a number (GetInt32) depending on the default. Keys that are in the file but unknown are ignored; keys missing from the file keep their default. That makes it safe to add a new setting in a later version.
The damaged file#
The program writes this is not json { to the file and creates a Settings object. The parse raises an error, the catch remembers it in cLoadError, and the defaults stay in place. A real program would also tell the user, or keep the bad file as settings.json.bad and start fresh.
What you learned#
- the user's special folders,
- defaults first, then the file on top,
- unknown and missing keys are fine,
- loading must never crash the program.
Exercises#
- Move the file to
ApplicationData\TutorialApp\settings.json(create the folder if needed withDirectory.CreateDirectory). - Add a
recentFilessetting that holds a list of up to five names. - Make
setValuerefuse an unknown key with an error. - Use the settings in a window: remember its position and size, and restore them when it opens (the tutorial A small text editor).