Files and folders
Read and write text files, build paths the right way, get information about files, copy, list and zip — with Path, Directory, File, StreamReader and ZipFile.
What you will learn#
- why you use
Path.Combine, - reading a whole file, line by line, and writing and appending,
- information about a file,
- listing a folder, copying, zipping, cleaning up.
The classes#
| Class | Job |
|---|---|
Path | work with names of files and folders (no disk access) |
File | read, write, copy, delete a file in one call |
Directory | create, delete, list folders |
FileInfo | information about one file: size, name, dates |
StreamReader / StreamWriter | read or write a file piece by piece (big files) |
ZipFile (System.IO.Compression) | make and open zip files |
The program#
# files and folders - Path, Directory, File, reading and writing, zip
load "dotnet.ring"
using {
"System"
"System.IO"
"System.IO.Compression"
}
func main
oPath = new Path()
oFile = new File()
oDirectory = new Directory()
# Never build paths by joining text: Path.Combine uses the right separator
cFolder = oPath.Combine([oPath.GetTempPath(),"ringdotnet_files"])
if oDirectory.Exists(cFolder)
oDirectory.Delete([ :path = cFolder, :recursive = True ])
ok
oDirectory.CreateDirectory(cFolder)
? "Folder created : " + oDirectory.Exists(cFolder)
# Write a text file and read it back
cNotes = oPath.Combine([cFolder,"notes.txt"])
oFile.WriteAllText([ :path = cNotes, :contents = "first line" + windowsnl() + "second line" + windowsnl() + "third line" ])
? "File exists : " + oFile.Exists(cNotes)
? "All the text : " + len(oFile.ReadAllText(cNotes)) + " characters"
aLines = oFile.ReadAllLines(cNotes).toList()
? "Lines : " + len(aLines) + ", the last is '" + aLines[len(aLines)] + "'"
# Append without erasing
oFile.AppendAllText([ :path = cNotes, :contents = windowsnl() + "fourth line" ])
? "After appending : " + len(oFile.ReadAllLines(cNotes).toList()) + " lines"
# Read a big file line by line with a reader
oReader = new StreamReader(cNotes)
nCount = 0
while not oReader.EndOfStream
oReader.ReadLine()
nCount++
end
oReader.Close()
? "Counted with reader: " + nCount
# Information about a file
oInfo = new FileInfo(cNotes)
? "Name and size : " + oInfo.Name + ", " + oInfo.Length + " bytes"
? "Extension : " + oPath.GetExtension(cNotes)
? "File name only : " + oPath.GetFileNameWithoutExtension(cNotes)
# Copy a file and list the folder
oFile.Copy([ :sourceFileName = cNotes, :destFileName = oPath.Combine([cFolder,"copy.txt"]) ])
? "Files in the folder: " + len(oDirectory.GetFiles(cFolder).toList())
# Zip a folder and unzip it somewhere else
cZip = oPath.Combine([oPath.GetTempPath(),"ringdotnet_files.zip"])
if oFile.Exists(cZip)
oFile.Delete(cZip)
ok
new ZipFile().CreateFromDirectory([ :sourceDirectoryName = cFolder, :destinationArchiveFileName = cZip ])
? "Zip size : " + new FileInfo(cZip).Length + " bytes"
oFile.Delete(cZip)
# Clean up
oDirectory.Delete([ :path = cFolder, :recursive = True ])
? "Cleaned up : " + (not oDirectory.Exists(cFolder))Folder created : 1
File exists : 1
All the text : 35 characters
Lines : 3, the last is 'third line'
After appending : 4 lines
Counted with reader: 4
Name and size : notes.txt, 48 bytes
Extension : .txt
File name only : notes
Files in the folder: 2
Zip size : 278 bytes
Cleaned up : 1How it works#
Paths#
Never build a path by joining texts with / or \. Path.Combine([a,b]) uses the right separator for the computer, and Path.GetTempPath() gives a folder where temporary files are allowed. Other Path helpers: GetFileName, GetExtension, GetFileNameWithoutExtension, GetDirectoryName. They only work on the text of a path; the file does not have to exist.
Ask before you act#
Directory.Exists(cFolder) and File.Exists(cFile) return true or false. Directory.Delete([ :path = cFolder, :recursive = True ]) deletes a folder and everything in it. Delete has a version with one parameter (an empty folder only) and one with two; the list of named arguments chooses the second.
Reading and writing#
| Need | Call |
|---|---|
| the whole file as one text | File.ReadAllText(path) |
| the lines as a collection | File.ReadAllLines(path).toList() |
| write (overwrites) | File.WriteAllText([ :path = p, :contents = text ]) |
| add at the end | File.AppendAllText([ :path = p, :contents = text ]) |
windowsnl() is Ring's line break for Windows (carriage return plus line feed).
Big files: a reader#
ReadAllText loads everything into memory. For a big file use a StreamReader: ReadLine() returns the next line, EndOfStream is true at the end, and Close() must be called to release the file.
Information, copy, list#
FileInfo gives Name, Length (the size in bytes), dates. File.Copy([ :sourceFileName = from, :destFileName = to ]), Directory.GetFiles(folder) and File.Delete(path) do what they say. Write and Copy have several versions, so they take a list of named values, like Round in the last lesson.
Zip#
ZipFile.CreateFromDirectory([ :sourceDirectoryName = folder, :destinationArchiveFileName = zipFile ]) compresses a whole folder; ZipFile.ExtractToDirectory opens it again.
Clean up#
A program that creates temporary files deletes them at the end. This tutorial's last line checks that the folder is gone.
What you learned#
- build paths with
Path, not with+, - ask
Existsbefore you read, - use a reader for big files and always close it,
FileInfogives the facts about a file.
Exercises#
- Write a program that counts the lines in every
.ringfile of a folder (Directory.GetFiles([ :path = cFolder, :searchPattern = "*.ring" ])). - Copy a file to the Documents folder (
Environment.GetFolderPath("MyDocuments")). - Find the biggest file in a folder with
FileInfo.Length. - Write a log: each run appends a line with the date and time.