【问题标题】:How do you update a text file in c# without getting rid of the existing content? [duplicate]如何在不删除现有内容的情况下更新 c# 中的文本文件? [复制]
【发布时间】:2020-07-25 08:18:06
【问题描述】:

我只想写入一个文本文件,而不覆盖文本文件中已有的内容。

string record = txtBxNumber.Text.PadRight(30) + txtBxDate.Text.PadRight(30)  + 
                txtBxPurchasedFrom.Text.PadRight(30) + txtBxShipTo.Text.PadRight(30) + 
                richTxBxDesc.Text.PadRight(30) + txtBxOrdered.Text.PadRight(30) + 
                txtBxUnit.Text.PadRight(30) + txtBxUnitPrice.Text.PadRight(30);

richTxtBxRecord.Text += record + "\n";

如果可能的话,作为奖励。我想根据 txtNumber.Text 的值更新文本文件中的一行。

【问题讨论】:

标签: c# input file-io


【解决方案1】:

这是您将文本附加到现有文本文件 https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netcore-3.1 的方式:

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string createText = "Hello and Welcome" + Environment.NewLine;
            File.WriteAllText(path, createText);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText);

        // Open the file to read from.
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}

【讨论】:

    【解决方案2】:
    File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
    

    【讨论】:

    • 虽然这段代码可能会解决问题,但一个好的答案还应该解释代码的什么以及它如何提供帮助。
    • @BDL 我会说“文件附加所有文本”是不言自明的......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2014-06-27
    • 2015-07-07
    • 2011-10-22
    相关资源
    最近更新 更多