File information
A file has more than its content — a size, times, attributes, a folder. This lesson reads and changes them with File and FileInfo: the size, the last write time, the read-only flag, copying with and without overwriting, and temporary files.
What you will learn#
FileInfo: name, extension, size and whether the file exists,- the times of a file and
Refresh(), - attributes and the read-only flag,
- the errors of a read-only file and of copying over an existing file,
- temporary files (
GetTempFileName), DirectoryInfoand the sizes of the files in a folder.
The tutorial Files and folders read and wrote the content of files. Here the file is the thing: how big it is, when it was written, whether it can be changed.
The program#
# file information - size, attributes, times, read-only files, temporary files and copying with File and FileInfo
load "dotnet.ring"
using {
"System"
"System.IO"
}
func main
oFile = new File()
oPath = new Path()
oDirectory = new Directory()
# A work folder with a random name; the program deletes it at the end. The names of the folders are not printed (they differ on each computer).
cFolder = oPath.Combine([ oPath.GetTempPath(), "ringdotnet-info-" + oPath.GetRandomFileName() ])
oDirectory.CreateDirectory(cFolder)
cFile = cFolder + "/report.txt"
oFile.WriteAllText([ :path = cFile, :contents = "Line one" + nl + "Line two" + nl ])
# 1. FileInfo describes one file: the name, the extension, the size and the folder. It is made from a path and it does not open the file.
oInfo = new FileInfo(cFile)
? "1. name: " + oInfo.Name + ", extension: " + oInfo.Extension + ", exists: " + yesNo(oInfo.Exists)
? " name without extension: " + oPath.GetFileNameWithoutExtension(cFile) + ", size: " + oInfo.Length + " bytes"
# 2. The times of a file: created, last written, last read. The program sets one to a known moment, so that the output is always the same.
oFile.SetLastWriteTime(cFile,(new DateTime).@New([ :year = 2024, :month = 3, :day = 15, :hour = 9, :minute = 30, :second = 0 ]))
oInfo.Refresh() # FileInfo keeps what it read: Refresh reads it again
? nl + "2. last written: " + oInfo.LastWriteTime.Format("yyyy-MM-dd HH:mm")
? " older than a day: " + yesNo(daysOld(oInfo) > 1)
# 3. Attributes: a file can be read-only, hidden, and more. They are flags in one value (a text such as "ReadOnly, Archive").
? nl + "3. attributes: " + oFile.GetAttributes(cFile)
oFile.SetAttributes(cFile,"ReadOnly")
? " after SetAttributes: " + oFile.GetAttributes(cFile) + ", IsReadOnly: " + yesNo(new FileInfo(cFile).IsReadOnly)
# 4. A read-only file is protected: writing to it raises an error. The program shows the message and then removes the flag.
try
oFile.WriteAllText([ :path = cFile, :contents = "new text" ])
? nl + "4. the file was changed"
catch
? nl + "4. writing failed: " + errorKind(cCatchError)
done
oFile.SetAttributes(cFile,"Normal")
oFile.WriteAllText([ :path = cFile, :contents = "new text" ])
? " after removing the flag: " + oFile.ReadAllText(cFile)
# 5. Copy. Copy raises an error when the target exists, unless the overwrite value is True. A copy has its own times.
cCopy = cFolder + "/copy.txt"
oFile.Copy([ :sourceFileName = cFile, :destFileName = cCopy ])
try
oFile.Copy([ :sourceFileName = cFile, :destFileName = cCopy ])
catch
? nl + "5. second copy: " + errorKind(cCatchError)
done
oFile.Copy([ :sourceFileName = cFile, :destFileName = cCopy, :overwrite = True ])
? " with overwrite = True: ok, size " + new FileInfo(cCopy).Length + " bytes"
# 6. Temporary files: GetTempFileName creates an empty file with a unique name in the folder for temporary files. The program that asked for
# it must delete it.
cTemp = oPath.GetTempFileName()
? nl + "6. a temporary file: exists " + yesNo(oFile.Exists(cTemp)) + ", size " + new FileInfo(cTemp).Length + " bytes"
oFile.Delete(cTemp)
? " after Delete: exists " + yesNo(oFile.Exists(cTemp))
# 7. The files of a folder with their sizes, from DirectoryInfo (the names are sorted so that the output is always the same)
oFolder = new DirectoryInfo(cFolder)
aNames = []
aItems = oFolder.GetFiles(NULL).toList()
for oItem in aItems
aNames + (oItem.Name + " (" + oItem.Length + " bytes)")
next
? nl + "7. in the folder:"
aSortedNames = sort(aNames)
for cName in aSortedNames
? " " + cName
next
oDirectory.Delete([ :path = cFolder, :recursive = True ])
func yesNo lValue
if lValue
return "yes"
ok
return "no"
# how many days ago the file was written
func daysOld oInfo
oNow = (new DateTime).Now
oSpan = oNow.Subtract(oInfo.LastWriteTime)
return oSpan.TotalDays
# the kind of an error: the name of the .NET exception ("System.IO.IOException"). The message of the exception also has the path of the
# file, which is different on each computer, so the program prints only the kind.
func errorKind cMessage
cText = trim(cMessage)
nStart = substr(cText,"DotNet Error: ")
if nStart > 0
cText = substr(cText,nStart + 14)
ok
nEnd = substr(cText,":")
if nEnd > 0
cText = left(cText,nEnd - 1)
ok
return cText1. name: report.txt, extension: .txt, exists: yes
name without extension: report, size: 18 bytes
2. last written: 2024-03-15 09:30
older than a day: yes
3. attributes: Archive
after SetAttributes: ReadOnly, IsReadOnly: yes
4. writing failed: System.UnauthorizedAccessException
after removing the flag: new text
5. second copy: System.IO.IOException
with overwrite = True: ok, size 8 bytes
6. a temporary file: exists yes, size 0 bytes
after Delete: exists no
7. in the folder:
copy.txt (8 bytes)
report.txt (8 bytes)This program uses a few generic functions (dnNew, dnStatic) where a class cannot be used. The lesson The generic functions explains them.
How it works#
File and FileInfo#
File has static methods that take a path (File.Exists, File.Copy, File.Delete...). FileInfo is an object made from a path: it gives Name, Extension, Length (bytes), Exists, IsReadOnly, the times and more, and it has the same actions as methods. FileInfo reads the information once and keeps it: when the file changes, Refresh() reads it again (step 2 needs it after the time was set).
Times#
A file has a creation time, a last write time and a last access time (each also in UTC). File.SetLastWriteTime(path, time) changes one; the program sets a known moment so that the output is the same every time. Backup tools and build tools compare the last write time of a source and its target to decide what is old.
Attributes#
GetAttributes returns the flags of a file as one text: Archive is set on Windows when a file was changed since the last backup, ReadOnly protects the file, Hidden hides it. Several flags are written with commas (ReadOnly, Archive). SetAttributes(path, "ReadOnly") replaces them all, so "Normal" removes the flags. On Linux and macOS the read-only flag follows the file permissions, and the output of step 3 differs a little there.
Errors#
Writing to a read-only file raises System.UnauthorizedAccessException. File.Copy onto an existing target raises System.IO.IOException unless the overwrite value is True. The message of such an error contains the full path, which is different on each computer, so the program prints only the kind of the error (the name of the exception) with the function errorKind.
Temporary files#
Path.GetTempFileName() creates an empty file with a unique name in the folder for temporary files and gives its path. The program that asked for it deletes it. For a whole work folder the program makes a name with Path.GetRandomFileName() and deletes the folder at the end, as this program does.
A folder and its files#
DirectoryInfo is to a folder what FileInfo is to a file. GetFiles(NULL) returns its files as FileInfo objects. The names are sorted before they are printed, because .NET does not define the order of the files it returns.
What you learned#
FileInfoandDirectoryInfo,- times,
Refresh()and the attributes, - read-only files and the exceptions of files,
- temporary files and folders.
Exercises#
- Write
isOlderThan(cFile, nDays)and use it to list the files of a folder that were not changed for a month. - Set the
Hiddenattribute and find the hidden files of a folder (GetFilesandAttributes). - Copy a file and compare the last write times of the two.
- Write
totalSize(cFolder)for a folder and all its subfolders.