【问题标题】:How to prevent overwriting in a text file?如何防止覆盖文本文件?
【发布时间】:2013-04-26 00:19:08
【问题描述】:

以下代码有问题。它应该防止覆盖文本文件中的记录。我的代码是这样的:

    public static void WritingMethod()
    {

    StreamWriter Sw = new StreamWriter("fileone.txt", true);
    string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
    + Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
    // I using the Environment.NewLine to insert new lines
    Console.WriteLine(output);      
    Sw.WriteLine(output + Environment.NewLine);

    Sw.Close();

}

它会覆盖记录。我想添加记录而不是覆盖它。

【问题讨论】:

  • 我觉得这很难相信。更改文件名并输出DateTime.Now。我怀疑该文件正在其他地方创建(附加)。可能是项目的 bin\debug 或 bin\release 目录。
  • 最有可能的错误出现在其他地方,因为您当前的示例完全符合您的要求 - 将行附加到文件中。旁注:请使用using 而不是.Close,因为它会导致更易读和更正确的代码(即正确关闭异常文件)。

标签: c# filestream streamwriter console.writeline


【解决方案1】:

使用File.AppendText打开你的StreamWriter

using (StreamWriter Sw = File.AppendText("fileone.txt"))
{
    string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
    + Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);

    Console.WriteLine(output);      
    Sw.WriteLine(output + Environment.NewLine);
}

【讨论】:

  • 如果第二个参数是true,他调用的构造函数会附加文件。 AppendText 调用该构造函数。 . .
  • 请注意,您的建议与原始代码相同 - 都为追加打开编写器 - 因此,虽然您的建议是正确的,但原始代码的行为应该相同。
猜你喜欢
  • 1970-01-01
  • 2012-11-20
  • 2015-04-09
  • 2016-10-12
  • 1970-01-01
  • 2015-08-26
  • 2014-05-26
  • 2013-06-06
  • 1970-01-01
相关资源
最近更新 更多