Search code examples
c#text-filesformclosing

How to close a text file with the event FormClosed or FormCloing?


I have the next code:

Process open_txt = new Process();
   public Form1()
   {
      InitializeComponent();
      open_txt.StartInfo.FileName = @"C:\Users\Desktop\Test.txt";
      open_txt.Start();
   }

With this code I open a .txt called File Test.txt to write on it.

I would like that when I close the form with the mouse (I mean, when I click the little red cross in the upper-right side, in other words, like all of us closes all the windows as well) the .txt file called Test.txt,also closes.

I know that I need to use the event FormClosed or FormClosing, but it doesn't work, I have this in this events, but doesn't close the .txt file.

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
   open_txt.Close();
}

or

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   open_txt.Close();
}

How I can close the .txt File


Solution

  • Use the Kill() method in your Form1_FormClosing() method:

    open_txt.Kill();