Working with files in C#

In this tutorial we will be working with files. How to create a file, edit it, rename a file make a copy an existing file or move it etc.

First thing you should do is to reference the System.IO namespace.

All the classes that will help you handle files are located in this namespace.

How to create a file and edit it?

You can create a file like this:

This will create a file “test.txt” in C: drive. File.Create() method can be used to create all kind of files. It returns a FileStream instance which you can use to work with the new file. I mean you can also write the above code as FileStream stream = File.Create(path);

Remember, it is not a good practice to use File.Create() method without saving the FileStream reference in a variable. Because otherwise you won’t be able to close the stream and you will get this error if you work with the file:

The process cannot access the file because it is being used by another process.

Whenever you get that error check your code for streams that are not closed. Always close a stream using the Close() method when you are done with it. Or a recommended way is to use the using Statement (I’ve used it below).

Okay, we have created a file but it is empty which makes it useless. Let’s add something to it:

FileStream is not the best choice if you adding only text to a file. For more on the text files check the next part.

How to create a text file or open a text file and edit it?

Here we will use the File.CreateText() method to create the file. It returns a StreamWriter instance which allows you to write text to the file.

How to copy, move, delete and rename a file?

To move or copy a file you can use File.Copy() and File.Move() methods.

To rename a file we will use the File.Move() method:

If you have any questions please don’t hesitate to post a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *