如何防止文本文件被覆盖?

问题描述 投票:0回答:2

我在使用以下代码时遇到问题。它应该防止覆盖文本文件中的记录。我的代码是这样的:

    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();

}

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

c# filestream streamwriter console.writeline
2个回答
4
投票

使用

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);
}

0
投票

我的编码同事,在 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.");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.