Aldo Huerta
Aldo Huerta

Reputation: 15

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

Upvotes: 0

Views: 1431

Answers (2)

D Stanley
D Stanley

Reputation: 152626

All you have is a reference to the Process, so it seems like the only thing you can do is Kill() the process. That seems fairly heavy-handed, but may do what you want.

It also may have unintended side-effects. What if the PC used Word to open text files, and when you kill the process you also lose any unsaved changes to other documents?

If you want more control over when the file is closed, then you probably need to embed an editor (or viewer) in your app rather than just farming out to the OS.

Upvotes: 3

itsme86
itsme86

Reputation: 19526

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

open_txt.Kill();

Upvotes: 1

Related Questions