如何在退出应用程序时清除txt文件 c#。

问题描述 投票:3回答:1

这是我的代码,用来填充我的txt文件,并显示在我的应用程序中。

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

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

我的问题是:当我退出我的应用程序时,我如何清除我的txt文件?

c# file exit
1个回答
1
投票

清空文本文件是非常直接的:只需将空字符串写入其中。

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

捕获应用程序的退出取决于你在应用程序中使用的框架。

例如,在WinForms上(看起来你正在使用它),你可以重写 OnFormClosed 的方法,并在那里清除你的文件。

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

    //clear your file
}

或者你可以处理 Application.ApplicationExit 事件,并从那里清除你的文件。

© www.soinside.com 2019 - 2024. All rights reserved.