Lesson 13 - Working with files and folders in C#. NET
In the previous lesson, Exceptions in C# .NET for the second time, we finished up with exceptions. In today's tutorial, we're going to describe common .NET classes which are not made for specific file types. They allow us to work with files and folders at the operating system level, which is certainly something we'll need in our applications.
File
The File class provides static methods for generally working with files. Files can be easily manipulated using the following methods:
- Exists("file") - Returns true if the specified file exists.
- Copy("Source", "Destination") - Copies a file from the source location to the destination. We can specify whether to overwrite existing files by entering the third parameter of the bool type.
- Move("Source", "Destination") - Moves the file to the target location.
- Delete("file") - Deletes the file.
We can read their attributes as follows:
- GetAttributes("file") - Returns the flag FileAttributes
type with the following flags:
- Normal
- ReadOnly
- Hidden
- System
- Directory
- Archive
- Temporary
- Compressed
- Offline
- Encrypted
We can also change attributes like this:
- SetAttributes( "file", FileAttributes) - Sets specified attributes to a specified file.
We can easily determine a file's individual times:
- GetCreationTime("file") - Returns the date and time when the file was created.
- GetLastAccessTime("file") - Returns the date and time of the last access.
- GetLastWriteTime("file") - Returns the date and time of the last modification.
We can also change them like this:
- SetCreationTime("file", DateTime) - Sets the date and time of the creation.
- SetLastAccessTime("file", DateTime) - Set the date and time of the last access.
- SetLastWriteTime("file", DateTime) - Sets time of the last modification.
All the methods for working with date and time can also be found with the "Utf" suffix for working with the international format (e.g. GetCreationTimeUtc()).
FileInfo
The FileInfo class is very similar to the File class, however, its methods
are not static. We create a FileInfo instance for one file and
its methods will automatically apply to this file. We'll use it mainly in case
we're dealing with one file so much that using File
would be
inefficient.
The class constructor takes the file, with which we're going to work, as a parameter:
FileInfo fileInfo = new FileInfo("file.txt");
Properties
Again, we can read or write the dates and times:
- CreationTime - The date and time of when the file was created.
- LastAccessTime - The date and time of the last access.
- LastWriteTime - The date and time of the last modification.
In the same way, there are versions whose name ends with "Utc" for the Universal Time.
We can read or modify attributes:
- Attributes - The attributes of the file in the FileAttributes flags format.
As well as determine other parameters for the file:
- Exists - Returns true if the file exists.
- Name - The name of the file.
- FullName - A filename including the path.
- Extension - The file extension.
- Directory - Returns an instance of the parent folder (of the DirectoryInfo type, see further).
- DirectoryName - Returns the path to the file without its name and the last slash.
- IsReadOnly - Whether the file is read-only.
- Length - The size of the file in bytes.
Methods
We can manipulate the file using the following methods:
- CopyTo("Destination") - Copies the file to the destination. We can enter the third parameter of the bool type specifying whether to overwrite existing files.
- Delete() - Deletes the file.
- MoveTo("Destination") - Moves the file to the target location.
- Refresh() - Refreshes the data in the FileInfo instance.
Fields
- Fullpath - The full path to the file.
- OriginalPath - The path as it was entered by the user.
Directory
Directory is similar to the File class but we use it for folders. The methods are also static, let's take a quick peek at them:
Methods
- CreateDirectory("folder") - Creates a given folder.
- Delete("folder") - Deletes an empty folder. If we pass
true
as the second parameter of the bool type, it'll delete the folder including files and subfolders. - Exists("folder") - Returns true if a given folder exists.
We work with dates and times using these methods:
- GetCreationTime("path")
- GetLastAccessTime("path")
- GetLastWriteTime("path")
- SetCreationTime("path")
- SetLastAccessTime("path")
- SetLastWriteTime("path")
- GetLogicalDrives() - Returns logical disks such as "C:\" as a string array.
- GetParent("folder") - Returns the parent folder.
- Move("Source", "Destination") - Moves the folder to the destination.
- GetDirectoryRoot( "folder") - Returns the root folder.
We can determine or modify the current folder as well:
- GetCurrentDirectory()
- SetCurrentDirectory("folder")
- EnumerateDirectories("folder") - Returns a collection of subfolders names in a given folder.
We can also pass a search pattern to the method as the second parameter which can include * or ?. An example pattern could be "*data??", which matches any text followed by text "data" and then by 2 arbitrary characters.
As the third parameter, we can specify SearchOption which is an enum with the TopDirectoryOnly and AllDirectories values. Meaning that we can scan subfolders like this as well.
- EnumerateFiles("folder") - Works pretty much the same as EnumerateDirectories, but it returns filenames.
- EnumerateFileSystemEntries("folder") - Works pretty much the same as EnumerateDirectories, but it returns both folders and files.
The GetDirectories(), GetFiles(), and GetFileSystemEntries() methods return the folder contents. The methods have the same parameters. The only difference is that instead of returning IEnumerable they return an array. IEnumerable allows us to work with the collection even before all the information is read from the disk. If we retrieve an array of many files, the operation can stop the application for a while.
DirectoryInfo
DirectoryInfo is a non-static version of the Directory class. The situation is the same as with File and FileInfo. Instances are created by entering the path to the constructor:
DirectoryInfo directoryInfo = new DirectoryInfo("C:\folder");
The class is suspiciously similar to the FileInfo class. This is because they're both inherited from a common ancestor - the FileSystemInfo class.
Properties
To read or change the attributes we use the same approach as the last couple of classes:
- Attributes - The attributes of the file in the FileAttributes flags format.
Manipulating dates and times is the same as well:
- CreationTime - The date and time of when the file has been created. Again, there are also versions suffixed with "Utc" for the Universal Time.
- LastAccessTime - The date and time of the last access.
- LastWriteTime - The date and time of the last modification.
Other folder properties will look familiar to us as well. They're the same as those of the File class:
- Exists - Returns true if the folder exists.
- Name - The name of the folder.
- FullName - The entire folder path.
- Extension - The file extension (if it's included in the path).
- Parent - The parent folder.
- Root - The root folder.
Methods
- Create() - Creates the folder.
- CreateSubdirectory("path") - Creates a subfolder/subfolders in the folder.
- Delete() - Deletes the folder, which must be empty.
- Delete(recursively) - If the parameter is true, it'll delete containing files and folders recursively as well.
- MoveTo("destination") - Moves the folder to the destination.
- Refresh - Refreshes the data in the DirectoryInfo instance.
To scan the folder, it's pretty much the same as with the Directory class. We have the EnumerateDirectories(), EnumerateFiles(), and EnumerateFileSystemInfos() methods. The name of the latter has changed. Again, they have their friends with the "Get" prefix which return an array. However, the difference here is that now DirectoryInfo, FileInfo, and FileSystemInfo instances are returned rather than strings!
Fields
- Fullpath - The full path to the folder.
- OriginalPath - The path as it was entered by the user.
We went over classes for working with files and classes for working with folders. You may also use the FileSystemInfo class, which includes the same methods that were common for both files and folders.
To complete the tutorial, we'll briefly go over the Path class.
Path
Path is a static class which provides the functionality and settings for working with paths to folders or files.
Methods
- ChangeExtension( "path", "extension") - Returns the path to the file with changed extension.
- Combine(array of strings) - Concatenates strings in a given array to the path and returns it. The method has two more overloads taking 2, 3, or 4 string parameters instead of an array.
- GetDirectoryName("path") - Returns the parent folder along with the full path.
- GetExtension("path") - Returns the file extension.
- GetFileName("path") - Returns the filename.
- GetFileNameWithoutExtension("path") - Returns the filename without the extension.
- GetFullPath("path") - Returns the absolute path of a specified path (e.g. from a relative path).
- GetInvalidFileNameChars() - Returns an array of invalid characters that can't be included in filenames.
- GetInvalidPathChars() - Returns an array of invalid characters that can't be included in paths.
- GetPathRoot( "path") - Returns the root of the path.
- GetRandomFileName() - Returns a unique string that can be used as a filename.
- GetTempFileName() - Creates a new temporary file on the disk and returns the path to it.
- GetTempPath() - Returns the path to the user's folder with temporary files.
- HasExtension("path") - Returns true if a given file has an extension.
- IsPathRooted("path") - Returns true if a path contains the root itself.
Fields
Some parts of paths are dependent on a specific platform, specifically, on a particular operating system. We can access them using the following fields:
- AltDirectorySeparatorChar - The alternative separator of folders, most often "/".
- DirectorySeparatorChar - Separator of folders, mostly "\".
- PathSeparator - Separator of paths, most often ";".
- VolumeSeparatorChar - Separator of volumes, mostly ''.
Congratulations, you've just finished the Files in C# .NET course! Now, you have enough knowledge to leave this area and continue with the Databases in C# .NET course where file manipulations will be handled by the database system.
In the next lesson, DocX - Working with MS Word Documents in C# .NET , we'll work with MS Word documents.