C# - How to Work with Files and Folders

In C# you have several ways to interact with files and folders, the most common are the File, Directory and FileInfo classes. Using these classes you can create, write, update and delete files and folders easily in .Net, here are some use cases!

For the following examples we will be using a folder located at C:\Test\Fileapp containing two subfolders someFolder, someOtherFolder and a file called SomeTextFile.txt as seen below:

folders-and-files-dotnet

We will use windows paths for the examples, but at the end we will demonstrate that it also works on Linux by deploying a small application. Below are some examples, it is not the complete set of methods of the different classes but it should cover the basics!

Directory listing

You can list all folders in a directory by using the GetDirectories method of the Directory class and provide it with the directory path:

var list = Directory.GetDirectories("C:\\Test\\Fileapp");

This will give you a list of strings containing C:\\Test\\Fileapp\\someFolder and C:\\Test\\Fileapp\\someOtherFolder, which are the two folders in the directory.

Listing files in a directory

You can list all files in a directory by using the GetFilesmethod of the Directory class and providing it with a path:

var list = Directory.GetFiles("C:\\Test\\Fileapp");

This will give you a list of strings containing C:\\Test\\Fileapp\\SomeTextFile.txt, which is the only file in that directory.

Note: if you want both files and folders you can use GetFileSystemEntries, for example: Directory.GetFileSystemEntries("C:\\Test\\Fileapp"); will return both the folders and the file.

Writing to and reading from a file

You can write to a file using the WriteAllText method of the File class and providing it with a path and the contents you want to overwrite, if the files does not exist it will be created:

File.WriteAllText("C:\\Test\\Fileapp\\SomeTextFile.txt", "Writing to a file");

You can read all contents from a file using ReadAllText:

var text = File.ReadAllText("C:\\Test\\Fileapp\\SomeTextFile.txt"); //text will be “Writing to a file”

This will return a string with the value we wrote earlier: "Writing to a file".

Check if a file or directory exists

You can use the File class to check if a file exists using the Exists method:

var fileExists = File.Exists("C:\\Test\\Fileapp\\SomeTextFile.txt");

or you can use the Directoryclass to check if a directory exists:

var fileExists = Directory.Exists("C:\\Test\\Fileapp");

Getting information about a file

Using FileInfo you can get information about a file:

var info = new FileInfo("C:\\Test\\Fileapp\\SomeTextFile.txt");

The above creates a new FileInfo object with properties that contains information about the file, such as:

  • CreationTime
  • LastWriteTime
  • Length

and many more! Check out FileInfo for more information.

Putting it all together in am application

Next we will make a small console application that takes a filepath as an input. It will then state LastWriteTime and overwrite the contents of that file with a given input. If it is given a directory it will list the contents of it and if it cannot find a file or directory in the path given, it will write an error. Here is the code:

Console.WriteLine("Enter a filepath in order to write to the file");
var inputFilePath = Console.ReadLine();

var isFile = File.Exists(inputFilePath);
var isDirectory = Directory.Exists(inputFilePath);

//If input is neither a file or directory
if (inputFilePath == null || (!isFile && !isDirectory))
{
    Console.WriteLine($"File \"{inputFilePath}\" does not exist");
    return;
}

//If input is a directory
if (isDirectory && inputFilePath != null)
{
    Console.WriteLine($"Directory provided, here is the content of it:{Environment.NewLine}");
    var directories = Directory.GetFileSystemEntries(inputFilePath);
    var directoryListString = string.Join(Environment.NewLine, directories) + Environment.NewLine;
    Console.WriteLine("Content:");
    Console.Write(directoryListString + Environment.NewLine);
}

//If input is a file
if (isFile && inputFilePath != null)
{
    var oldFileContents = File.ReadAllText(inputFilePath);
    Console.Write($"File found, current file content is:{Environment.NewLine}{oldFileContents}{Environment.NewLine}");

    FileInfo fileInfo = new FileInfo(inputFilePath);
    Console.WriteLine($"File was last edited: {fileInfo.LastWriteTimeUtc}");

    Console.WriteLine("Input text to overwrite the file content... (ctrl + c to abort)");
    var newFileContent = Console.ReadLine();
    File.WriteAllText(inputFilePath, newFileContent);
}

Console.WriteLine($"All done!");

Before we can execute this on our linux system we need to build the app and move it to a folder where we can execute it, I have moved it to my home folder in a "fileapp" folder, below are the files (:~$ are bash commands):

:~$ cd /home/peterdrasmussen
:~$ ls
fileapp
~$ ls fileapp
FileApp.deps.json  FileApp.dll  FileApp.exe  FileApp.pdb  FileApp.runtimeconfig.json

We can then run the program using dotnet <target dll> and give it a file path that does not exist:

:~$ dotnet fileapp/FileApp.dll
Enter a filepath in order to write to the file
/home/peterdrasmussen/test
File "/home/peterdrasmussen/test" does not exist

We will keep the example that we started with and create the same two folders and the SomeTextFile.txt file as before:

:~$ mkdir /home/peterdrasmussen/test
:~$ mkdir /home/peterdrasmussen/test/someFolder
:~$ mkdir /home/peterdrasmussen/test/someOtherFolder
:~$ touch /home/peterdrasmussen/test/SomeTextFile.txt
:~$ dotnet fileapp/FileApp.dll
Enter a filepath in order to write to the file
/home/peterdrasmussen/test
Directory provided, here is the content of it:

Directories:
/home/peterdrasmussen/test/someFolder
/home/peterdrasmussen/test/SomeTextFile.txt
/home/peterdrasmussen/test/someOtherFolder

All done!

In the above we create the folder structure and the file, we then point our application to the directory to list it. The only thing remaining is to write something to the file and see its contents:

:~$ dotnet fileapp/FileApp.dll
Enter a filepath in order to write to the file
/home/peterdrasmussen/test/SomeTextFile.txt
File found, current file content is:

File was last edited: 04/15/2023 17:41:50
Input text to overwrite the file content... (ctrl + c to abort)
ABCDEF
All done!
:~$ cat /home/peterdrasmussen/test/SomeTextFile.txt
ABCDEF

As we can see the file in the above had no initial content, after we have used our application and written ABCDEF to it, we can then CAT it to get the contents of the file.

That is all

I hope you enjoyed this post, let me know in the comments what you think and if it was helpful! I certainly enjoyed setting this up.