【问题标题】:StreamWriter outputs ... at end of .txt fileStreamWriter 输出 ... 在 .txt 文件的末尾
【发布时间】:2021-11-13 23:31:53
【问题描述】:

我正在将文本框中的一些文本写入 .txt 文件,在 40 个字符之后,它只是放了一个“...”

代码如下:

//defining the path as a string
string fileName1 = @"C:\Users\-----\AppData\Local\" + nameTextBox.Text + " FileName.txt";
        //checking if the file exists
        if (!File.Exists(fileName))
        {
            
            //if file does exist, open the file and edit it
            using (StreamWriter writer = File.CreateText(fileName))
            {
                //using stream writer to write the file System.IO.StreamWriter(@"C:\Users\-----\AppData\Local\" + NameTextbox.Text + "FileName.txt"); //open the file for writing.
                writer.Write(writingTextBox.Text); //write text box contents to the file. 
                writer.Close();
                writer.Dispose();
            }
        }
        else
        {
            //if the file does not exist, create new file
            System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\Users\-----\AppData\Local" + nameTextBox.Text + "FileName.txt");
            writer1.Write(writingTextBox); //write the textbox contents to the file.
            writer1.Close();
            writer1.Dispose();
        }

请帮忙,

谢谢。

【问题讨论】:

  • 您可能在else 分支中输入错误 - writer1.Write(writingTextBox); 应该是writer1.Write(writingTextBox.Text);
  • 谢谢,现在可以了!

标签: c# visual-studio winforms streamwriter


【解决方案1】:

如果您只是编写简单的文本数据并且每次都想覆盖它,那么您最好使用WriteAllText

string fileName = @"C:\Users\-----\AppData\Local\" + nameTextBox.Text + " FileName.txt";

File.WriteAllText(fileName, writingTextBox.Text));

无需检查文件是否存在,有不同的处理。

如果您想追加到文件,那么您也可以使用AppendAllText。但是你必须先检查文件是否存在。

【讨论】:

  • 谢谢,这很有帮助!
猜你喜欢
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 2015-02-02
  • 2020-11-17
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多