I am trying to add a logfile to a program I am making, but when I tell the main thread to exit (using Application.ExitThread()), logstrmWriter is suddenly null before it ever gets there. This is a very simple script.
private static FileStream appLogStream;
internal static string logFile;
internal static StreamWriter logstrmWriter;
public static void Main()
{
logFile = Application.StartupPath + @"\Archiver.log";
appLogStream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read);
TextWriter logtxtWriter = Console.Out;
StreamWriter logstrmWriter = new StreamWriter(appLogStream);
if(!console) Console.SetOut(logstrmWriter);
Application.ApplicationExit += new EventHandler(OnApplicationExit);
Application.Run();
}
internal static void OnApplicationExit(object sender, EventArgs e)
{
active = false; Console.WriteLine("Main thread is shutting down. Sending Interrupt...");
Archiver.Stop(); Console.WriteLine("Shutdown. Log and Exit");
Console.WriteLine();
logstrmWriter.Flush();
logstrmWriter.Close();
logstrmWriter.Dispose();
}
You’re creating a local variable that hides the static variable in question. As such, you never initialize
logstrmWriterat all.