File operations I/O

This tutorial will present you the basic file operations in C#, like creating a file, writing text to a file, opening / reading a file, retrieving file information, copying and moving a file and more...

In this tutorial we're going to code in a C# Windows Application project, so start this project in the Microsoft Visual C# .NET environment.

Creating a file

As most of the tasks in C#, creating a file is really easy to accomplish, but - of course - you must know how.

On the form created inside the project, add a TextBox and a Button (txtFileName and btnCreateFile).

Now let's do the coding which is as easy as it was adding the controls, a two step process. Right click the form and choose View code so you can see the code.

First thing you should do is solve the namespace to System.IO, which is the namespace used for file operations (input / output).

using System.IO;

Creating a text file

Now back on the form design, double click the button btnCreateFile and the Click event will be created, where you'll use this:

private void btnCreateFile_Click(object sender, System.EventArgs e)

{

File.CreateText(@txtFileName.Text);

}

The line inside the event creates a text file at the path specified in the TextBox. Note that the '@' is used so that the \ (backslash) isn't considered an escape character.

If you typed C:\MyFile.txt in the TextBox, File.CreateText will create a file named MyFile.txt in the root of C:.

The file can have any extension you want, not just txt or no extension at all, but consider that here we created a text file (see CreateText) and therefore the file is written using ASCII characters.

Creating a binary file

A binary file is created the same way, just that instead of using CreateText() you use Create(). At first you won't notice any difference between the text file and the binary file but it matters a lot because it is stored differently. You use the text file for storing (doh) text and the binary file for storing.

Writing text to a file

Let's not create an empty file this time, let's write something into the file when it is created. First we need a StreamWriter so declare one in Form1.cs:

private System.IO.StreamWriter SW;

Now in the Click event of btnCreateFile use the following lines:

private void btnCreateFile_Click(object sender, System.EventArgs e)

{

// Create the file

SW = File.CreateText(@txtFileName.Text);

// Write using the StreamWriter

SW.WriteLine("Life without knowledge is death in disguise");

// Close the writer

SW.Close();

}

It's straightforward what is going on here, with the help of the StreamWriter we write a string to the file. Hence, type a path for the file again in the TextBox and press the btnCreateFile button, this time not only it creates a file at the specified path but also adds the text inside SW.WriteLine("").

Opening and reading a text file

Now that we have the file created, let's open it. On the same project, the same form (Form1) add a button btnOpenFile and a TextBox txtFileContent.

In the code, now. First we need to create a StreamReader and an int variable:

private System.IO.StreamReader SR;

private int FileChar;

Then doubleclick the button btnOpenFile to get the btnOpenFile_Click() event.

private void btnOpenFile_Click(object sender, System.EventArgs e)

{

// Open the file

SR = File.OpenText(@txtFileName.Text);

// Loop trough each character in the file

while((FileChar = SR.Read()) != -1)

{

// Show the current char

//MessageBox.Show(Convert.ToChar(FileChar).ToString());

// Display the text in the TextBox

txtFileContent.Text += Convert.ToChar(FileChar);

}

// Close the reader

SR.Close();

}

As you can see here, we loop trought the file for each character. SR.Read() moves to the next character every time, but when SR.Read() returns -1 (no character), the loop will end.

If you want to see how the loop is done, you can uncomment the line with the MessageBox and you'll see each time SR.Read() passes to the next character.

The integer variable FileChar holds the current character. But why an integer and not a char, you ask? Because the characters are stored in ASCII and that's also why we later convert it using Convert.ToChar().

Checking if a file exists

You'll often have to check if a file exists at a specified path, so let's see how it's done. Create a new button on the form named btnFileExists and doubleclick it so you can get the Click event, where you'll use the following:

private void btnOpenFile_Click(object sender, System.EventArgs e)

{

if(File.Exists(@txtFileName.Text))

{

MessageBox.Show("It's there!");

}

else

{

MessageBox.Show("I can't find it...");

}

}

Simple, we test using File.Exists() to see if the file specified in the path in txtFileName exists.

Maybe you noticed that if you type a path to an inexistent file in the TextBox and click the btnOpen button you'll get an ugly error. Well that's the case in which we can use File.Exists().

Retrieving file information

Getting file attributes like Read-only, Hidden, CreationTime, DateTime, LastAccessTime, LastWriteTime or the directory in which the file resides is really easy in .NET. They are all done using the FileInfo class. Let's see an example.

In the code create a new instance of FileInfo:

private System.IO.FileInfo FI;

Add a new button btnFileInfo and doubleclick it to get the Click event. Now that we're at the event, check out the following code:

private void btnFileInfo_Click(object sender, System.EventArgs e)

{

FI = new FileInfo(@txtFileName.Text);

// Show in which directory the file resides

MessageBox.Show(FI.DirectoryName.ToString());

// Get the file's extension

MessageBox.Show(FI.Extension.ToString());

// When the file was last accessed

MessageBox.Show(FI.LastAccessTime.ToString());

// When the file suffered modifications

MessageBox.Show(FI.LastWriteTime.ToString());

if((FI.Attributes & FileAttributes.ReadOnly) != 0)

{

MessageBox.Show("Read-only");

}

if((FI.Attributes & FileAttributes.Hidden) != 0)

{

MessageBox.Show("Hidden");

}

if((FI.Attributes & FileAttributes.Archive) != 0)

{

MessageBox.Show("Archive");

}

if((FI.Attributes & FileAttributes.System) != 0)

{

MessageBox.Show("System");

}

}

There are other attributes that we didn't use in the code but you can easily figure them out thanks to IntelliSense.

Copying a file

Let's copy the MyFile.txt file from one place to another. Add to the form two TextBoxes - txtCopyFrom and txtCopyTo. Also add a button btnCopy. Doubleclick the newly created button and we now need to code the Click event.

private void btnCopy_Click(object sender, System.EventArgs e)

{

File.Copy(txtCopyFrom.Text, txtCopyTo.Text, false);

}

Yes, it's that simple, txtCopyFrom.Text is the source and txtCopyTo.Text is the destination path. False is set because we don't want any file with the same name on the destination to be overwritten.

Moving a file

To finish our project, let's add to the form two TextBoxes - txtMoveFrom and txtMoveTo - and a Button btnMove which you'll doubleclick to get to the event:

private void btnMove_Click(object sender, System.EventArgs e)

{

File.Move(txtMoveFrom.Text, txtMoveTo.Text);

}

Just as simple, but don't forget that you shouldn't implement just a line of code for doing file operations, like in this case. You also have to handle exceptions... for example if you try to move a file to a path where there's a file with the same name you'll get an ugly exception (actually they are all ugly).

There will probably be another tutorial following this one that handles more advanced file operations because this was just a superficial covering of the subject for those in a hurry and there's much, much more to say about IO in .NET.

Rate this tutorial

Current Comments

this is giving error when you are clicking any button when text box is empty.actually it must give messge type the text into the text box

by Andrei Pociu on Friday, June 10th 2005 at 03:37 AM

I wanted to focus on file operations, not on form validation.
Moreover, when opening a file I suggest using OpenFileDialog which I covered here, and when saving a file, use SaveFileDialog.

by jayesh on Thursday, September 15th 2005 at 03:21 AM

Excell style of making complex topic(i/o) to simple
Thanx....

by Manmohan Singh Sarwa on Monday, October 3rd 2005 at 09:35 AM

It was Simple thing But i want to know from somebody how to access the extra fields related to a file like summery, keyword, etc.

by Andrei Pociu on Monday, October 3rd 2005 at 09:40 AM

I successfully used the class at codeproject.com/csharp/detailedfileinfo.asp in an application, for getting such information. Good luck!

by Arman on Sunday, January 29th 2006 at 08:19 AM

Hi,
How can i find if a given string exists in a text file or not ?

by DIVIA on Tuesday, February 21st 2006 at 05:42 AM

How to navigate the file pointer within a file

by Emmit on Sunday, February 26th 2006 at 06:00 PM

Loved the article! Thanks. Question: How would one open rich text files and write their contents to a destination rich text file?

by Firoj Shaikh on Sunday, August 13th 2006 at 05:51 AM

If I want to update data in file
Then How can I do it??
Please suggest solution

by TheProgrammer on Monday, October 23rd 2006 at 11:40 AM

nice description...

by utpal kumar on Tuesday, June 5th 2007 at 05:48 AM

a good tutorial to begin with.

by Asha on Wednesday, July 4th 2007 at 01:21 AM

also add to this article about retrieving files from specific folder/directory

by grrrrrrrrrrreat! on Tuesday, July 24th 2007 at 02:42 PM

that's grrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreat!

by Success on Tuesday, October 9th 2007 at 06:03 AM

Excellento, Thks!!!

by Sudhanwa on Tuesday, November 13th 2007 at 07:05 AM

there is a text file in which every line has a new IP address. i need to open this file thru a c code, take the ip address line by line(1 ip at a time) and send it as an argument to icmp program. any ways to do it???

by Craig on Monday, February 18th 2008 at 12:50 PM

thanks thats great really helpfull only one comment

please put in suggestions for where Public and Private declarations go. I nearly bailed out as a newbee but stuck it out and feel happy

I have request, which can you dedicate a part to deleting and updating the file?

Fx show how to delete the whole file and maybe parts of the file?

Thanks in advance and once again great work!

by bedroom design ideas on Saturday, August 13th 2011 at 06:24 AM

yielding in a necropolis modify. I was exploit uninterested at cognition as no acquisition here at duty. So was intelligent dressed any blogs and came crossways your book, character win man I likable what you wrote Inspirational and rattling essential.

bedroom design ideas

by bedroom design ideas on Saturday, August 13th 2011 at 06:35 AM

yielding in a necropolis modify. I was exploit uninterested at cognition as no acquisition here at duty. So was intelligent dressed any blogs and came crossways your book, character win man I likable what you wrote Inspirational and rattling essential

by sms on Tuesday, August 16th 2011 at 01:17 AM

The classification is depend on the realistic. There whatsoever capitalist that mix the determining with the worsened one. You moldiness trounce it understandably.

by heartburn remedies on Friday, August 19th 2011 at 10:19 PM

The classification is depend on the realistic. There whatsoever capitalist that mix the determining with the worsened one. You moldiness trounce it understandably.

by be yourself quotes on Monday, November 7th 2011 at 07:29 PM

Cool. I might just try my luck again with this, before I failed, I didn't have your post as a guide. Thanks!

by low interest credit cards on Monday, December 12th 2011 at 05:34 AM

Use System.Windows.Forms.Cursor.Position to get the cursor position in screen coordinates.I admire the important information you offer within your content. I'll bookmark your web site and have my kids examine up the following typically.

by Valentines Treasure Hunt on Thursday, January 12th 2012 at 03:59 AM

Well this kind of information is really worth searching for, good information for readers and a value for you as will definitely show the quality of the writer.
Valentines Treasure Hunt

by Valentines Treasure Hunt on Thursday, January 12th 2012 at 04:00 AM

Well this kind of information is really worth searching for, good information for readers and a value for you as will definitely show the quality of the writer.
Valentines Treasure Hunt

by Valentines Treasure Hunt on Thursday, January 12th 2012 at 04:00 AM

Well this kind of information is really worth searching for, good information for readers and a value for you as will definitely show the quality of the writer.
Valentines Treasure Hunt

by Valentines Treasure Hunt on Thursday, January 12th 2012 at 04:00 AM

Well this kind of information is really worth searching for, good information for readers and a value for you as will definitely show the quality of the writer.
Valentines Treasure Hunt

by Valentines Treasure Hunt on Thursday, January 12th 2012 at 04:00 AM

Well this kind of information is really worth searching for, good information for readers and a value for you as will definitely show the quality of the writer.
Valentines Treasure Hunt

by Margarita on Saturday, January 14th 2012 at 01:41 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by oakley sunglas on Tuesday, March 6th 2012 at 11:57 PM

Read many articles, but found your article very thoughtful, very unique insights