How to clear txt file when exiting C # application

this is my code to populate my txt file and display in my application.

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

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

      

My question is, how do I clear the txt file when I quit the application?

+3


source to share


1 answer


Deleting a text file is pretty easy: just put an empty line in it:

StreamWriter file = new StreamWriter("opslag_kentekens", false);
file.Write(String.Empty);
file.Close();

      

Capturing the application exit depends on the framework you are using in your application.



For example, in WinForms (it looks like you are using it) you can override the OnFormClosed

main form method of the application and clear the file there:

protected override void OnFormClosed(FormClosedEventArgs e)
{
    base.OnFormClosed(e);

    //clear your file
}

      

Or you can handle the event Application.ApplicationExit

and clear the file from there.

+1


source







All Articles