【问题标题】:How to enter multiple data from textbox to txtfile without overwrite [duplicate]如何在不覆盖的情况下从文本框输入多个数据到文本文件[重复]
【发布时间】:2015-09-13 03:23:50
【问题描述】:

在 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");

所以当我点击我的按钮时,在 textBox1.text 中输入的文本 必须去我的 opslag_kentekens.txt。这工作正常,但是当想在我的 txt 中输入新文本时,它会覆盖第一个输入的文本。我想要每个文本相互输入。我该怎么做呢? (对不起我的英语不好)。

【问题讨论】:

    标签: c# textbox


    【解决方案1】:

    file.WriteLine() 不会保留您现有的文本。 您可以改用File.AppendAllText(String, String)

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

    【讨论】:

    • 成功了:)。我在想他们有一些超负荷的东西要写,但这更简单:)
    • 是的。 AppendAllText(String, String) 将打开一个文件,将指定的字符串附加到文件中,然后关闭文件。如果文件不存在,此方法创建一个文件,将指定的字符串写入文件,然后关闭文件。你需要的一切:)
    【解决方案2】:

    试试这个

    new StreamWriter("opslag_kentekens", true);

    【讨论】:

      【解决方案3】:

      将您的构造函数更改为use the append overload 并将其设置为true,这应该可以工作。

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

      【讨论】:

        【解决方案4】:

        基本上,您正在查看附加到文件:

        来自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 语法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多