Total Users Online: 1





C# Tutorial: Writing Text Files

Partial codes that may help you further your coding education.

C# Tutorial: Writing Text Files

Postby yang » Sun Aug 03, 2008 3:01 am

Writing Text Files in C# .NET

There are many amazing things you can do with an application, but one of the most useful is to interact with the user's files. Most programs store data in files, and this can be used for numerous reasons.

Here we are using the .NET Framework (I use v3.5). First, add the following statement to the top of the code file, next to the other "using" statements:

Code: Select all
using System.IO;


The .NET Framework provides a namespace for working with the data - System.IO (short for Input/Output). Now - on to reading the most basic of files - the text file!

Writing Data

It is easier to write data to a file. Here's what you do:

We use a StreamWriter class (in the System.IO namespace) to write the data:

Code: Select all
string path = @"C:\myfile.txt";
StreamWriter sw = new StreamWriter(path)


The object is not static - you create a new object (which we here call "sw"), and use the constructor to choose a file. Replace the string "path" with your desired path - and don't forget to include the @ symbol, otherwise C# interprets the backslashes as escape sequences. Next, is the easy part:

Code: Select all
string bufferOne = "This is text 1.";
string bufferTwo = "This is text 2.";
sw.Write(bufferOne);
sw.Write(bufferTwo);


This writes the following text to the text file:

This is text 1.This is text 2.


If we wanted to have the text on separate lines, we could instead use:

Code: Select all
sw.WriteLine(bufferOne);
sw.WriteLine(bufferTwo);


This produces the following result in the text file:

This is text 1.
This is text 2.


It depends on the situation as to which method to use. However, you must use whichever one is most appropriate for the situation.

At the end, we must finish off by closing and unreferencing the StreamWriter object. If you do not call Close(), the code may not work:

Code: Select all
sw.Close();
sw.Dispose();


And that's all there is to it! Remember that you do not have to pass a string in to the Write() or WriteLine() - the method is overloaded, so you can use many data types, including char, byte, int and even boolean. Happy writing!
"To know, is to know that you know nothing. That is the meaning of true knowledge." - Confucius
"知之为知之,不知为不知,是知也。" - 孔子
User avatar
yang
The Big Kahuna
 
Posts: 70
Joined: Thu Jul 31, 2008 12:02 am
Location: Portland, OR

Return to Code Snippets/Tutorials

Who is online

Users browsing this forum: No registered users and 0 guests

cron