I have a simple C# Console Application and I want to execute a function when the user is closing the Console Application. So I need an event probably, which fires a function on pressing Ctrl + C, clicking the close button or writing something into the console to shut down. I tried every single code snippet on Stackoverflow and other pages but none of them worked on all cases. One solution worked for everything during debugging the Application in Visual Studio, however on running the compiled exe File in a Console Prompt, it didn't work on Ctrl + C and clicking the close button. Can anyone help me?
Here's my code in the Main class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
namespace BankClient
{
class Program
{
private static DB _db;
private static string _notUpdatedUsersCsvFilePath;
static void Main(string[] args)
{
BankServer server = new BankServer();
_db = new DB();
_notUpdatedUsersCsvFilePath = "not_updated_users.csv";
if (File.Exists(_notUpdatedUsersCsvFilePath))
{
string[] lines = File.ReadAllLines(_notUpdatedUsersCsvFilePath);
if (lines.Length > 0)
{
Console.WriteLine($"Es sind noch unbearbeitete Einträge von Kunden vorhanden, welche nicht in der Datenbank aktualisiert werden konnten:");
foreach (string l in lines)
{
Console.WriteLine($"{l.Split(';').First().Trim()} {l.Split(';').Last().Trim()}");
}
Console.WriteLine();
}
}
Console.WriteLine("Fetching DB...");
if (_db.fetchDB()) Console.WriteLine("Fetched DB successfully.");
else
{
Console.WriteLine("An error occured whilst fetching DB!");
Console.ReadLine();
return;
}
Console.WriteLine();
foreach (Kunde k in _db.Kunden)
{
Console.WriteLine($"- {k.Vorname} {k.Nachname} ({k.Id}) -> Kontostand: {k.Kontostand}");
}
Console.WriteLine();
Kunde kunde = _db.Kunden.Find(k => k.Id == 1);
if (kunde == null)
{
Console.ReadLine();
return;
}
kunde.Kontostand += 100;
kunde.ChangeMade = true;
Console.WriteLine($"{kunde.Vorname} {kunde.Nachname} ({kunde.Id}) -> Kontostand: {kunde.Kontostand}");
Console.ReadLine();
onClosing();
}
private static bool onClosing()
{
bool error = false;
Console.WriteLine("Stopping application...");
Console.WriteLine("Updating DB...");
Dictionary<bool, string> tmpDB = _db.saveDB();
if (tmpDB.ContainsKey(true))
{
Console.WriteLine("Updated DB successfully.");
}
else
{
error = true;
Console.WriteLine(tmpDB[false]);
foreach (Kunde k in _db.Kunden)
{
if (k.ErrorMessage != null)
{
File.AppendAllText(_notUpdatedUsersCsvFilePath, $"[{DateTime.Now}];" + $"{{id: {k.Id}, vorname: \"{k.Vorname}\", nachname: \"{k.Nachname}\", kontostand: {k.Kontostand.ToString().Replace(',', '.')}, filiale: {k.Filiale}, status: {k.Status}, errorMessage: \"{k.ErrorMessage}\"}}" + Environment.NewLine);
}
}
}
if (!error)
{
Thread.Sleep(5000);
Environment.Exit(-1);
return true;
}
Thread.Sleep(10000);
return false;
}
}
}
Best regards, Steven