Click here to Skip to main content
15,395,181 members
Articles / Desktop Programming / WPF
Posted 16 Sep 2014


35 bookmarked

Working with Files (Using C# and .NET Framework)

Rate me:
Please Sign up or sign in to vote.
4.64/5 (20 votes)
16 Sep 2014CPOL10 min read
This article explains the basic knowledge about the File class in .NET Framework that comes handy when working with the file system, to create, edit, modify or delete the files or directories.


This article tries to explain the basics about the files and the directories in the system. How can a developer develop a software that would interact with the File system, create new files, modify or edit the currently existing files and/or move them to new locations in the file system or delete them at all.

This article has the code explained for the total beginners for the .NET Framework and C# and the File or Directory class. It would help them understand what these classes are, and what they can do with them. 


Working with Files (specially images) is considered to be a hard work, and a tough time is given to the developer in developing the projects. But .NET Framework has really cool API, that helps you to do all these functions very fastly. 

You don't even have to go to the next line while writing the code to create a new file if you're using .NET Framework. Just provide the fileName and location and you're done!


In the .NET Framework there are classes defined for each process and functionality. While defining the input and output classes, they merged them up in one namespace, System.IO namespace. It contains all of the particular type of functions and methods that you can use to work with the Input and the Output streams. Working with Directories and Files is a part of this namespace. Because File and Directories are made on the Harddisk drive of your computer, and extracting or writing data to it is a part of input and output that is why. File and Directory class is a part of this namespace.

Since we're only going to work with Files and Directories only namespace we're going to talk about is the System.IO itself, and not any of the derivative of it, like memory etc.

Above link has the full detailed desription and the information about the namespace and the methods that it can perform.


Directories are also known as Folders in Windows (and maybe other OS too, since I've only used Windows, I won't bother confusing you people). In the OS there are many folders that are used to group similar data together so that it might be easy in future to find them using the name of the folder.

We can work on these directories inside the file system using the Directory class of the .NET Framework. You can use a Directory object and point it to some location, so that you can work on them. Directory and File methods don't have any constructor so don't bother passing a value to it, or using new keyword to it. 

Since the Directories and Files are alike in functions, the Files is a bit vast chapter so I will explain it, Directory class has the same methods for Create, Move and Delete, but just Directory appeneded to the method to tell the developer that this method must have a directory to work upon.

Above link is for the Directory class in .NET Framework and you can easily learn it at the MSDN documentation. 


Here is the major topic that would be covered in this tutorial article. .NET Framework developers have done a lot of work trying to bring up a easy-to-write API for the developers so that they have to write less do more thing.

Files in real are just a binary data on the harddisk that our OS using some algorithms and encoding reads as file using their extensions in the File Allocation Table (FAT; you must have heard this name while formatting the drives. Yes, it is the same term, this is the File System version and the version of the table that would be created by the OS for the allocation of the files in the system) and then showing them relatively on the users' screens. 

public static class File

This is the basic declaration of the File class, and you can see from the declaration that you cannot use the new keyword on it, since the class is static.

Creating a new File

The first process as in all cases is the creation. The file creation process is really simple in C#, we just have to pass a string that contains the locations of the (new - to be created) file. And the .NET Framework handles the remaining stuff for us.


You can replace the location with the location where you want to store the file. It must be string. The close method that I have called onto this function is required to close the stream and allow other threads and processes to use the File if they want to. Otherwise the "File is being used by another process" error will be shown to the user. To minimize this, atleast you, yourself should close the Stream of the File and free it up. 

However the Close function is not a required class and you can continue the processing and executing without even calling that function and the program won't complain. 

Writing the Data

Files are generally creating in the form of binary, and they contain a blob of binary data that is stored on the harddisk, then they are converted to different files using extension and schemes but in depth they're all just binary. So, you can write the data to a file that will be further converted to the binary. It is just us, trying to write and get back the fancy data.

.NET framework provides a lot of functions to write the data, depending on the type of data that you're having. You can write string data, bytes, arrays etc. All of these functions are called using the same name, but just the parameters are different as they're passed with different data type. 

File.WriteAllBytes(string fileLocation, byte[] bytes); 

..above code would write all of the bytes of the data to the file. 

In all of the codes and methods of the File and Directory class, the location of the file or directory comes first then the value of the arguments are passed to work on. If there is a function where location comes later, I will be new to it.

You can even pass down the string data, to the method, or arrays. Arrays are used to write lines. So that a data with lines of data would be passed to a new method to write the data in the form of a line. For example, 

// create new array
string[] lines = {"First", "Second", "Third"};

// loop for each of the line
foreach (string line in lines) 
   // write it
   File.WriteAllText(fileLocation, line);

..above method is used to write each of the string inside the array. But, as mentioned there is a default method for the arrays. That is

File.WriteAllLines(fileLocation, lines); // lines is array

..this would write each of the occurance of the string in the variable. Comes handy when there are a lot of lines and you want to do the coding efficiently. Let the .NET framework handle the code for you and just pass the array and the location.

Reading the Data

Reading the data from the file is as simple as writing the data. Same single line code with the same names but just Read instead of Write.

.NET Framework developer have paid a great attention to the requirement of the developers and have come up with a great tool. As you passed string, arrays and bytes to the file you will access and extract the bytes, strings and arrays from the files using the same methods. For example the following code, 

File.ReadAllText(fileLocation); // returns string
File.ReadAllLines(fileLocation); // returns string[] 
File.ReadAllBytes(fileLocation); // returns byte[]

..same methods and same return values. You can then work on the data returned to you and process the data or what so ever the task is. 

If there is a file that has no string information stored you can still get the bytes information, and guessing the schemes of the file you can easily get the data in the form that you want to get. 

Moving the files

This is the module where File gets used less and Directory get used more. Since in this module you will move the file from one location to another location. 

In the File there is a method called Move that gets the location of two directories and passes the file at first location to the location of the second argument. You might not get it that soon, but, have a look 

File.Move(fileLocation, newLocation);

Above code would move the file at the fileLocation to a new location at newLocation. You must first check whether there is any file present there or not. It is not required way, but a good way of doing so. So that in the code execution there isn't any exception raised.

Moving files, as already said isn't a job of File itself, it is a work of directory where you just change the directory for that file and move it to a new location on the drive.

Deleting the File

Deleting a file is the last stage of its life. You can call a simple and single line code to delete the file and .NET Framework would remove the file from the system.


..just the location of the file is required. It is a good approach to first check for the existance of the file in the system to prevent any error from rasing. 

Returning to Directory... mentioned, Directory reflects the methods and functions of the File class and you can use those methods with just a slight difference in the names of the functions. 

Directory.CreateDirectory(dirLocation); // creates directory
Directory.Delete(dirLocation); // deletes directory

..all of the functions are alike. But there is only one thing different about them. It is that they contain more files and directories in them, whereas a file can only contain its data. For this purpose, developers added some more functions that would work on this property of directory. 

Directory within Directory

There can be more or multiple directories inside each directory and you can get those directories from the directory you're currently refering to. 


This returns an enumeration list that you can then convert to a List<string> and start working with or showing the names etc. For example, this code

List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));

It gets the names of the directories present in there in a list of string data type. Each directory has this property, and this method can be called on it. Enabling you to go through each folder on the user's system.

File within Directory

Inside a directory, there can be multiple files within a directory, for them to be found the framework has a different function ready. 

Directory.EnumerateFiles(currentDirectory); // returns the files

You can call the very same function to get the names in the string on this too, that has been used in the above block for conversion.

Some general tips

While working with the Files and directories you need to make sure of the following, 

  1. Argument is not null.
  2. Filename is accurate and the extension is added.
  3. File exists, while reading or writing the content. 

These single if else blocks are not actually required by the framework or the code itself but are usefull to minimize the errors. For example you can check whether the file exists or not and then run a code to create it and work on it later rather than just getting an annoying exception and the stoppage of the software execution. 

As in the above paragraphs, I have mentioned the closage of the streams and some other precautions. These are just to make sure the application runs smoothly and leaves less chances for any exception. I know, developers hate unwanted exception.

Application attached..

..contains the basic source code included and the software built and tested. You can use it, to work with the system's file system. Same code is being used on that software, so don't worry, the stuff you've read or learnt here is present there no more tutorial was included. 

Same amount of System.IO has been tutored in this article as is in the application. 

Points of Interest

System.IO also supports the input and output streams from the memory, so that you can directly even store the data in the memory and extract data from memory. 


First post. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Afzaal Ahmad Zeeshan
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

GeneralMy vote of 5 Pin
Аslam Iqbal22-Sep-14 1:42
professionalАslam Iqbal22-Sep-14 1:42 
Question...A Confidence Builder! Pin
jediYL18-Sep-14 13:45
professionaljediYL18-Sep-14 13:45 
AnswerRe: ...A Confidence Builder! Pin
Afzaal Ahmad Zeeshan19-Sep-14 0:10
mveAfzaal Ahmad Zeeshan19-Sep-14 0:10 
GeneralThoughts Pin
PIEBALDconsult17-Sep-14 4:44
professionalPIEBALDconsult17-Sep-14 4:44 
GeneralRe: Thoughts Pin
Nelek17-Sep-14 7:06
protectorNelek17-Sep-14 7:06 
GeneralRe: Thoughts Pin
PIEBALDconsult17-Sep-14 7:59
professionalPIEBALDconsult17-Sep-14 7:59 
GeneralRe: Thoughts Pin
Nelek17-Sep-14 8:26
protectorNelek17-Sep-14 8:26 
GeneralRe: Thoughts Pin
PIEBALDconsult17-Sep-14 8:35
professionalPIEBALDconsult17-Sep-14 8:35 
GeneralRe: Thoughts Pin
Nelek17-Sep-14 9:08
protectorNelek17-Sep-14 9:08 
GeneralRe: Thoughts Pin
PIEBALDconsult17-Sep-14 9:18
professionalPIEBALDconsult17-Sep-14 9:18 
GeneralRe: Thoughts Pin
peterkm20-Nov-16 21:47
Memberpeterkm20-Nov-16 21:47 
GeneralRe: Thoughts Pin
Richard MacCutchan22-Sep-14 0:19
mveRichard MacCutchan22-Sep-14 0:19 
GeneralRe: Thoughts Pin
Nelek22-Sep-14 4:33
protectorNelek22-Sep-14 4:33 
GeneralRe: Thoughts Pin
jfriedman11-Jul-16 11:04
Memberjfriedman11-Jul-16 11:04 
GeneralRe: Thoughts Pin
Nelek12-Jul-16 3:24
protectorNelek12-Jul-16 3:24 
GeneralRe: Thoughts Pin
jfriedman12-Jul-16 4:06
Memberjfriedman12-Jul-16 4:06 
Well my bad, my comment was directly intended @ the author for the most part. Didn't mean to confuse anyone or any `concepts`....Unsure | :~
GeneralRe: Thoughts Pin
Nelek12-Jul-16 4:28
protectorNelek12-Jul-16 4:28 
QuestionC++ version Pin
Ștefan-Mihai MOGA16-Sep-14 19:05
professionalȘtefan-Mihai MOGA16-Sep-14 19:05 
AnswerRe: C++ version Pin
Afzaal Ahmad Zeeshan17-Sep-14 4:24
mveAfzaal Ahmad Zeeshan17-Sep-14 4:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.