-2

Another way to say it is this: I want a program that logs the amount of times you've pressed a button. To do this I'd need a StreamWriter to write to a text document the number of times and a StreamReader to read the number of times as to display it when you start up the program. If there is an easier way, feel free to share it. But my question is: How can I make it so that it only writes in one line, and whenever it wants to write again to it, deletes the whole thing and puts in the new input?

Nether
  • 1,081
  • 10
  • 14

1 Answers1

1

The below will write to the file C:\log.txt. By setting the 2nd parameter to false, it will overwrite the contents of the file.

using (StreamWriter writer = new StreamWriter("C:\\log.txt", false))
{
    writer.Write("blah");
}

To guarantee the file is always overwritten every time it is used, place the StreamWriter call in a different method like so:

public void DoStuff()
{
    for(int i = 0; i < 20; i++)
    {
        WriteStuff("blah" + i);
    }
}

private void WriteStuff(string text)
{
    using (StreamWriter writer = new StreamWriter("C:\\log.txt", false))
    {
        writer.Write(text);
    }
}
user1666620
  • 4,800
  • 18
  • 27
  • This is not what I want. When your method writes "blah" 5 times, they're all on different lines. I want it to overwrite all on one line, so you'd call the method and it'd write 'blah', say you call it again and you should only see 'blah' again. The old blah should have been written over do you understand what I'm trying to say? – Nether Aug 07 '15 at 23:01
  • 1
    @Nether I think your problem might have been how you originally implemented the code... – user1666620 Aug 07 '15 at 23:24