我在使用以下代码时遇到问题。它应该防止覆盖文本文件中的记录。我的代码是这样的:
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);
}
我的编码同事,在 C# 中我们有函数
File.Exists(path);
如果返回值为 true,则继续运行你的程序
using System;
using System.IO;
class Program
{
static void Main()
{
string FilePath = "C:\\Users\\Harley Quinn\\MyCuteLittlePudding.txt";
if (File.Exists(FilePath))
{
Console.WriteLine("File already exists. Cannot overwrite.");
}
else
{
using (StreamWriter writer = new StreamWriter(FilePath))
{
writer.WriteLine("Hello, Gotham!");
}
Console.WriteLine("File created successfully.");
}
}
}