A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
File operations I/OThis 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... |
On Wednesday, November 10th 2004 at 12:45 PM By Andrew Pociu (View Profile) ![]() ![]() ![]() ![]() (Rated 4.8 with 57 votes) |
|||||||||||
|
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 fileAs 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).
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:
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 fileLet'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:
Now in the Click event of btnCreateFile use the following lines:
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 fileNow 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:
Then doubleclick the button btnOpenFile to get the btnOpenFile_Click() event.
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 existsYou'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:
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 informationGetting 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:
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:
There are other attributes that we didn't use in the code but you can easily figure them out thanks to IntelliSense. ![]() Copying a fileLet'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.
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 fileTo 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:
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. |
||||||||||||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
||||||||||||
|
||||||||||||
Current CommentsGreat tutorial, lots of useful information! Thanks!
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
I wanted to focus on file operations, not on form validation.
Moreover, when opening a file I suggest using <b>OpenFileDialog</b> which I covered <a href='http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html' target='_blank'>here</a>, and when saving a file, use <b>SaveFileDialog</b>.
Excell style of making complex topic(i/o) to simple
Thanx....
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.
I successfully used the class at codeproject.com/csharp/detailedfileinfo.asp in an application, for getting such information. Good luck!
Hi,
How can i find if a given string exists in a text file or not ?
How to navigate the file pointer within a file
Loved the article! Thanks. Question: How would one open rich text files and write their contents to a destination rich text file?
If I want to update data in file
Then How can I do it??
Please suggest solution
nice description...
a good tutorial to begin with.
also add to this article about retrieving files from specific folder/directory
that's grrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreat!
Excellento, Thks!!!
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???
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
Thanks
Very Effective
really great tutorial.
wowwwwwww good article.its help me a lotttt.thanks
Good article for beginners......can u provide file operation with exception handling
Related Tutorials
Related Source Code
C# Job Search