File and Directory classes contain different static methods for manipulating the files, directories, and subdirectories. These classes exist in the System.IO namespace. So, let’s inspect some of the most used methods of both classes.

For the complete navigation of this series check out: C# Back to Basics.

File Methods

WriteAllText(string path, string contents) creates a new file and writes content to that file. If the target file already exists, it will overwrite it:

WriteAllLines(string path, string[] contents) creates a new file and writes a specified string array, then it closes the file:

ReadAllText(string path) opens the file in the specified path, reads all the lines as a string, and then closes the file:

ReadAllLines(string path) opens a text file, reads all lines of the file as a string array, and then closes the file:

Delete(string path) Deletes the specified file:

Move(string sourceFileName, string destFileName)moves a specified file to a new location:

AppendAllText(string path, string contents) opens a file, appends the content to the file, and then closes the file. If a file doesn’t exist, it will create a file, write the content, and close the file. This method is useful if we want to append a new content without overriding the previous one:

AppendAllLines(string path, IEnumerable<string> contents) appends lines to the file and then closes the file:

Directory Methods

CreateDirectory(string path) creates directories and subdirectories on the specified location unless they already exist. It returns a DirectoryInfo object for the existing directory:

Delete(string path) deletes an empty directory from a specified path:

Delete(string path, bool recursive) deletes the specified directory, and if it is stated, all the subdirectories and files in that directory:

Move(string sourceDirName, string destDirName) moves a file or directory and its contents to a new location:

Conclusion

Well done. With this article, we have finished with the basics of C#. In our next module, we are going to talk about object-oriented concepts in C# and how to integrate it into our code.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.