如何防止在文本文件中覆盖?
问题描述:
我在下面的代码中遇到了问题。它应该防止覆盖文本文件中的记录。我的代码是这样的:如何防止在文本文件中覆盖?
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();
}
它覆盖记录。我想添加记录,而不是覆盖它。
答
打开StreamWriter
使用File.AppendText
:
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);
}
+1
如果第二个参数为“true”,那么他正在调用的构造函数会附加该文件。 'AppendText'调用构造函数。 。 。 – 2013-04-26 01:02:06
+1
请注意,您的建议与原始代码完全相同 - 都是打开的作者追加 - 因此,虽然您的建议是正确的,但原件应该表现相同。 – 2013-04-26 01:03:17
我觉得很难相信。更改文件的名称并输出'DateTime.Now'。我怀疑文件正在创建(追加)在别的地方。可能是项目的bin \ debug或bin \ release目录。 – 2013-04-26 01:05:13
最有可能的错误是其他地方,因为您当前的示例行为完全按照您的要求 - 将行添加到文件。附注:请使用'using'而不是'.Close',因为它会导致更易读和更正确的代码(即正确关闭异常文件)。 – 2013-04-26 01:05:26