Paths and the environment
Programs that work on every computer build paths with Path.Combine, ask the system for special folders and read settings from environment variables. This lesson shows each one.
What you will learn#
- building and taking apart paths with the
Pathclass, - relative and absolute paths,
- cleaning a text so that it is a valid file name,
- special folders (documents, temporary files),
- environment variables with a default value,
- how .NET
nullarrives in Ring.
Why not add strings?#
"reports" + "\" + "2024" works on your computer only: other systems use /, and an extra separator or a missing one breaks the path. Path.Combine chooses the separator of the system and never doubles it.
The program#
# paths and the environment - building paths safely, splitting them, special folders and environment variables
load "dotnet.ring"
using {
"System"
"System.IO"
}
func main
oPath = new Path()
# 1. Build a path with Combine, never with + "\": Combine uses the right separator for the system and never doubles it
cFile = oPath.Combine(["reports","2024","january.txt"])
? "1. Combine: " + cFile
? " Combine with a rooted second part restarts the path: " + oPath.Combine(["reports","/etc/hosts"])
# 2. Take a path apart
cFull = "C:\data\reports\2024\summary.final.txt"
? nl + "2. file name : " + oPath.GetFileName(cFull)
? " without suffix : " + oPath.GetFileNameWithoutExtension(cFull)
? " extension : " + oPath.GetExtension(cFull)
? " folder : " + oPath.GetDirectoryName(cFull)
? " change the extension: " + oPath.ChangeExtension(cFull,".csv")
# 3. A path can be relative (to the current folder) or absolute (complete): GetFullPath makes it absolute
cAbsolute = oPath.GetFullPath("data.txt")
? nl + "3. is 'data.txt' rooted? " + yesNo(oPath.IsPathRooted("data.txt")) + "; its full path is rooted? " + yesNo(oPath.IsPathRooted(cAbsolute))
? " it ends with the same name: " + yesNo(oPath.GetFileName(cAbsolute) = "data.txt")
# 4. Characters a file name may not contain
cBad = "report: 1/2?.txt"
cGood = cBad
for cChar in ["\","/",":","*","?",'"',"<",">","|"] # the characters Windows does not allow in a name
cGood = substr(cGood,cChar,"_")
next
? nl + "4. '" + cBad + "' becomes '" + cGood + "'"
# 5. Special folders: do not write the user's name into your code, ask the system
oEnvironment = new Environment()
cDocuments = oEnvironment.GetFolderPath("MyDocuments")
? nl + "5. the documents folder exists? " + yesNo(new Directory().Exists(cDocuments))
? " the temporary folder exists? " + yesNo(new Directory().Exists(oPath.GetTempPath()))
# 6. Environment variables: settings from outside (a password, a folder, a mode). Always provide a default.
oEnvironment.SetEnvironmentVariable([ :variable = "RINGDOTNET_MODE", :value = "fast" ])
? nl + "6. RINGDOTNET_MODE = " + oEnvironment.GetEnvironmentVariable("RINGDOTNET_MODE")
cMissing = oEnvironment.GetEnvironmentVariable("RINGDOTNET_NOT_SET")
if isobject(cMissing) # .NET null comes to Ring as an object that IsNull()
cMissing = "(default)"
ok
? " a variable that is not set: " + cMissing
oEnvironment.SetEnvironmentVariable([ :variable = "RINGDOTNET_MODE", :value = NULL ])
# 7. The system: which one runs the program
? nl + "7. 64-bit process? " + yesNo(oEnvironment.Is64BitProcess) + ", the new line is " + len(oEnvironment.NewLine) + " character(s) long"
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. Combine: reports\2024\january.txt
Combine with a rooted second part restarts the path: /etc/hosts
2. file name : summary.final.txt
without suffix : summary.final
extension : .txt
folder : C:\data\reports\2024
change the extension: C:\data\reports\2024\summary.final.csv
3. is 'data.txt' rooted? no; its full path is rooted? yes
it ends with the same name: yes
4. 'report: 1/2?.txt' becomes 'report_ 1_2_.txt'
5. the documents folder exists? yes
the temporary folder exists? yes
6. RINGDOTNET_MODE = fast
a variable that is not set: (default)
7. 64-bit process? yes, the new line is 2 character(s) longHow it works#
Combine and split#
Path.Combine joins parts: give a list of the parts (Combine([a, b, c])) or name them (Combine([ :path1 = a, :path2 = b ])). Careful: if a later part is rooted (starts with a separator or a drive), the earlier parts are dropped. That is correct behavior but a classic surprise when the part comes from user input.
GetFileName, GetFileNameWithoutExtension, GetExtension, GetDirectoryName and ChangeExtension take a path apart or change one piece. Use them instead of searching for dots and slashes yourself: summary.final.txt has two dots, and only the last one starts the extension.
Relative and absolute#
data.txt means "in the current folder" and the current folder changes with how the program is started. GetFullPath makes the path complete. Programs that should find their own files build the path from a known place, not from the current folder.
Valid names#
Windows does not allow \ / : * ? " < > | in a name. Step 4 replaces each by _. (Path.GetInvalidFileNameChars() has the list of the current system, but it returns a .NET array of characters, so the tutorial writes the list itself.)
Special folders#
Environment.GetFolderPath("MyDocuments") and Path.GetTempPath() give folders that exist on every computer; never write C:\Users\Ali\... in a program.
Environment variables#
An environment variable is a named setting that lives outside the program (set by the user, a script or a server). SetEnvironmentVariable sets one for this process; GetEnvironmentVariable reads it. A variable that does not exist gives null, and .NET null arrives in Ring as an object (not a text): test it with isobject(value) (or dnIsNull(value), which also accepts a text), then use your default. Never print a password or a key that came from a variable.
What you learned#
Path.Combineand the otherPathmethods,- relative or absolute,
- valid file names,
GetFolderPath,GetTempPath,- environment variables and the null object.
Exercises#
- Write
uniqueName(cFolder, cName)that adds(2),(3)to the name until the file does not exist. - Read a variable
MYAPP_FOLDERfor the data folder, with the documents folder as the default. - List the extensions found in a folder with how many files each has.