Get up to 80 % extra points for free! More info:

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("fi­le") - 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:

  • GetCreationTi­me("file") - Returns the date and time when the file was created.
  • GetLastAccessTi­me("file") - Returns the date and time of the last access.
  • GetLastWriteTi­me("file") - Returns the date and time of the last modification.

We can also change them like this:

  • SetCreationTi­me("file", DateTime) - Sets the date and time of the creation.
  • SetLastAccessTi­me("file", DateTime) - Set the date and time of the last access.
  • SetLastWriteTi­me("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. GetCreationTi­meUtc()).

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("Desti­nation") - 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("Desti­nation") - 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

  • CreateDirecto­ry("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:

  • GetCreationTi­me("path")
  • GetLastAccessTi­me("path")
  • GetLastWriteTi­me("path")
  • SetCreationTi­me("path")
  • SetLastAccessTi­me("path")
  • SetLastWriteTi­me("path")
  • GetLogicalDri­ves() - Returns logical disks such as "C:\" as a string array.
  • GetParent("fol­der") - 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:

  • GetCurrentDirec­tory()
  • SetCurrentDirec­tory("folder")
  • EnumerateDirec­tories("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("fol­der") - Works pretty much the same as EnumerateDirec­tories, but it returns filenames.
  • EnumerateFile­SystemEntries("fol­der") - Works pretty much the same as EnumerateDirec­tories, but it returns both folders and files.

The GetDirectories(), GetFiles(), and GetFileSystemEn­tries() 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.
  • CreateSubdirec­tory("path") - Creates a subfolder/sub­folders in the folder.
  • Delete() - Deletes the folder, which must be empty.
  • Delete(recursi­vely) - If the parameter is true, it'll delete containing files and folders recursively as well.
  • MoveTo("desti­nation") - 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 EnumerateDirec­tories(), EnumerateFiles(), and EnumerateFile­SystemInfos() 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.
  • GetDirectoryNa­me("path") - Returns the parent folder along with the full path.
  • GetExtension("pat­h") - Returns the file extension.
  • GetFileName("pat­h") - Returns the filename.
  • GetFileNameWit­houtExtension("pat­h") - Returns the filename without the extension.
  • GetFullPath("pat­h") - Returns the absolute path of a specified path (e.g. from a relative path).
  • GetInvalidFile­NameChars() - Returns an array of invalid characters that can't be included in filenames.
  • GetInvalidPat­hChars() - Returns an array of invalid characters that can't be included in paths.
  • GetPathRoot( "path") - Returns the root of the path.
  • GetRandomFile­Name() - 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("pat­h") - Returns true if a given file has an extension.
  • IsPathRooted("pat­h") - 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:

  • AltDirectorySe­paratorChar - The alternative separator of folders, most often "/".
  • DirectorySepa­ratorChar - Separator of folders, mostly "\".
  • PathSeparator - Separator of paths, most often ";".
  • VolumeSeparator­Char - 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.


 

Previous article
Exceptions in C# .NET for the second time
All articles in this section
Files and I/O in C# .NET
Skip article
(not recommended)
DocX - Working with MS Word Documents in C# .NET
Article has been written for you by David Capka Hartinger
Avatar
User rating:
2 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities