1

i need some help with entering data in a txt.file. this is the following code:

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

label20.Text = File.ReadAllText("opslag_kentekens");

So when i click on my button the text what is entered in the textBox1.text has to go to my opslag_kentekens.txt. this works fine but when want to enter new text to my txt, it overwrites the first entered text. I want every text whats entered among each other. How do i do this? (sorry for my bad english).

4 Answers4

2

file.WriteLine() will not keep your existing text. You can use File.AppendAllText(String, String) instead:

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

Liem Do
  • 933
  • 1
  • 7
  • 13
  • Nailed it :). I was thinking they had some overload to write, but this was simpler :) – Noctis Jun 26 '15 at 08:57
  • Yeah. `AppendAllText(String, String)` will Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file. Everything you need :) – Liem Do Jun 26 '15 at 08:59
1

try this

new StreamWriter("opslag_kentekens", true);

user1010186
  • 171
  • 1
  • 4
  • 14
1

Change your constructor to use the append overload and set it to true, that should work.

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

Basically you're looking at appending to a file:

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

Usually, for writing (not appending), it's easier to use the File Write methods, as they are cleaner and convey your meaning better:

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

Even better and cleaner, look @Liem's answer, which is the same but with the correct Append syntax.

Noctis
  • 11,507
  • 3
  • 43
  • 82