Things You'll Need:
- Microsoft Visual C# 2008 Epress (free)
-
Step 1
Note: This article assumes you have installed Microsoft Visual C# 2008 Express Edition. You may download it for free from here: http://www.microsoft.com/express/download/
Open Microsoft Visual C#. Click on "Project..." to the right of Create in the Recent Projects area of the Start Page.
The New Project window will open. Click on "Windows Forms Application", enter a Name, and click OK.
By default, the only form in the project will be called "Form1" and you will be in Design mode for that form. -
Step 2
Hover over the Toolbox on the left side of the screen and the Toolbox will automatically expand. Click and drag a Button control, under the Common Controls category, onto the form.
-
Step 3
Double click the button and you will now be in the code window for Form1. The method for the button click will already be created.
-
Step 4
Add "using System.IO;" just beneath "using System.Windows.Forms;". This namespace contains the StreamWriter object that we will be using to write out to the file.
-
Step 5
Within the button1_Click method, add the following code:
try
{
using (StreamWriter MyStreamWriter = new StreamWriter("C:\\TestFile.txt"))
{
MyStreamWriter.WriteLine("C# is the bomb! ");
MyStreamWriter.Write("Sorry Java.");
MyStreamWriter.WriteLine(" :(");
MessageBox.Show("Done.");
}
}
catch (Exception MyError)
{
MessageBox.Show("Error writing file: " + MyError.Message);
}
The try/catch statements will capture any error that occurs and will pop-up a MessageBox with the error displayed.
Our instance of the StreamWriter is called MyStreamWriter and is contained within a "using" clause. This will cause the memory used by MyStreamWriter to be disposed of effectively.
MyStreamWriter.WriteLine() writes the string out to the file and adds a carriage return and a line feed.
MyStreamWriter.Write() just writes the string out to the file.
Note that when we created our instance of the Streamwriter, we had to use double backslashes for the path: "C:\\TestFile.txt"
This is due to a single slash being a special character in a string. -
Step 6
Go up to the toolbar and run the program by clicking on the Start Debugging (f5) play button.
NOTE: If you got any kind of error after clicking the play button, you probably made a syntax error when typing the code. Reread the code until you find and correct the error and try again. -
Step 7
The form will take a moment and then pop up. Clicking on the button1 will display the message.
-
Step 8
Go to your C drive and open the file. Awesome!
-
Step 9
One final note: If you want to append to the file instead of overwriting it, use this instead:
using (StreamWriter MyStreamWriter = new StreamWriter("C:\\TestFile.txt",true))
The second parameter to the StreamWriter constructor is a boolean value that indicates whether or not you want to append the data to the file.















