开发者

Writing to text file gives me errors

开发者 https://www.devze.com 2023-01-24 11:31 出处:网络
The code below gives me three compiler errors. They are as follows: The type or namespace name \'TextWriter\' could not be found (are you missing a using directive or an assembly reference?)开发者_高

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. 开发者_高级运维
  3. The name 'File' does not exist in the current context
  4. 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);
   } 
}


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".


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.


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") {
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号