如何在不覆盖的情况下将多个数据从文本框输入到txtfile

本文关键字:文本 数据 输入 txtfile 覆盖 情况下 | 更新日期: 2023-09-27 17:59:46

我需要一些在txt.file中输入数据的帮助。这是以下代码:

StreamWriter file = new StreamWriter("opslag_kentekens");
string opslag_kentekens = textBox1.Text;
file.WriteLine(opslag_kentekens);
file.Close();
label20.Text = File.ReadAllText("opslag_kentekens");

因此,当我点击我的按钮时,文本框1.text中输入的内容必须转到我的opslag_kentekens.txt。这很好,但当想在我的txt中输入新文本时,它会覆盖第一个输入的文本。我希望每一条文本都是相互输入的。我该怎么做?(对不起我英语不好)。

如何在不覆盖的情况下将多个数据从文本框输入到txtfile

file.WriteLine()不会保留现有文本。您可以使用File.AppendAllText(String, String)代替:

https://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx

尝试这个

new StreamWriter("opslag_kentekens",true);

更改构造函数以使用append重载,并将其设置为true,这应该会起作用。

StreamWriter file = new StreamWriter("opslag_kentekens", true);

基本上,您看到的是附加到文件:

来自msdn:

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. 
        using (StreamWriter sw = File.CreateText(path)) 
        {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }   
    }
    // This text is always added, making the file longer over time 
    // if it is not deleted. 
    using (StreamWriter sw = File.AppendText(path)) 
    {
        sw.WriteLine("This");
        sw.WriteLine("is Extra");
        sw.WriteLine("Text");
    }   
    // Open the file to read from. 
    using (StreamReader sr = File.OpenText(path)) 
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) 
        {
            Console.WriteLine(s);
        }
    }
}

通常,对于写作(而不是附加),使用File Write方法更容易,因为它们更干净,更好地传达你的意思:

var some_text = "this is some text";
var out_path =  @"C:'out_example.txt";
System.IO.File.WriteAllLines(out_path, some_text);

更好、更干净的是,看看@Liem的答案,它是相同的,但具有正确的Append语法。