Error approaching C #

I am trying to catch the end of my form, so when the user exits, he saves "User exited" to a text file, this is my code:

private void mainForm_FormClosing(object sender, FormClosingEventArgs e) { if (String.IsNullOrEmpty(directory)) { Close(); e.Cancel = false; } else { string time = DateTime.Now.ToString("hh:mm"); TextWriter msg = new StreamWriter(directory, true); msg.WriteLine(" (" + time + ") == " + uName + " Has Left The Chat == "); msg.Close(); Close(); e.Cancel = false; } } 

My problem is that I get this error:

"Make sure you don't have an infinite loop or infinite recursion"

Any ideas on how to fix this?

+4
source share
3 answers

You cannot call the Close () method from closing a form. Remove all Close () calls and it will work.

 private void mainForm_FormClosing(object sender, FormClosingEventArgs e) { if (String.IsNullOrEmpty(directory)) { e.Cancel = false; } else { string time = DateTime.Now.ToString("hh:mm"); using(TextWriter msg = new StreamWriter(directory, true)) { msg.WriteLine(" (" + time + ") == " + uName + " Has Left The Chat == "); msg.Close(); } e.Cancel = false; } } 
+8
source

You do not need to call the Close() method. Someone already called it if the mainForm_FormClosing event was mainForm_FormClosing .

+3
source

The event " mainForm_FormClosing " is executed due to the closing of the form, there is no need to call "Close ();" in terms of If and Else.

If you do this, you will get a β€œSystem.StackOverflowException Fix”

+2
source

All Articles