user770022
user770022

Reputation: 2959

Writing to text file gives me errors

The code below gives me three compiler errors. They are as follows:

  1. The type or namespace name 'TextWriter' could not be found (are you missing a using directive or an assembly reference?)
  2. The name 'File' does not exist in the current context
  3. The name 'filename' does not exist in the current context

Can anyone provide some clarification as to why these errors are occurring, and how I can fix them?

private void button1_Click(object sender, EventArgs e)
{
   using (TextWriter writer = File.CreateText(filename.txt)) {
      writer.WriteLine("First name: {0}", textBox1.Text);
      writer.WriteLine("Last name: {0}", textBox2.Text);
      writer.WriteLine("Phone number: {0}", maskedTextBox1.Text);
      writer.WriteLine("Date of birth: {0}", textBox4.Text);
   } 
}

Upvotes: 0

Views: 1039

Answers (3)

Donut
Donut

Reputation: 112915

First of all, you are missing a using directive for the System.IO namespace, which is where both the TextWriter and File classes are located. Add the following line at the top of your file, this should resolve your first two errors:

using System.IO;

Secondly, the File.CreateText() method takes a string as a parameter. In your code, "filename.txt" is not a string. Use this line instead:

using (TextWriter writer = File.CreateText("filename.txt") {

Upvotes: 1

Matthew Jones
Matthew Jones

Reputation: 26190

For Error 1 and Error 2, make sure you are using System.IO;

For Error 3, if the name of the file to be read is "filename.text", make sure you place the quotes like so:

using (TextWriter writer = File.CreateText("filename.txt"))

because otherwise it is trying to find a variable filename and property txt rather than the string "filename.txt".

Upvotes: 2

dcp
dcp

Reputation: 55467

File.CreateText(filename.txt)

You need to put the filename in quotes if it's a filename, or use a proper variable name otherwise.

e.g.

File.CreateText("filename.txt");

or

File.CreateText(path);

And as donut said, add using System.IO to top of file.

Upvotes: 1

Related Questions