Search code examples
c#.netwindows-cestringbuilderstreamwriter

Why is my file not being written to?


I'm creating a "debug/log" textfile to try to see which "background threads" are running when the app I'm working on hangs.

First, as they're activated, I'm storing them in a StringBuilder:

public static StringBuilder ActiveBackgroundThreads = new StringBuilder();

There are quite a few (nearly 50) "Background Threads" (so the original developer named them, although I'm not sure they are truly such) which get toggled on and off, and I've added the additions to the StringBuilder there, like so:

private void InitializeBackgroundThread_PDALoginTerminate( bool add )
{
    try
    {
        if ( add )  
        {
            pc.PDALoginTerminate += new PendingCommands.PDALoginTerminateEventHandler( DeinitLoginDialogs );
            SSCS.ActiveBackgroundThreads.Append("DeinitLoginDialogs\r\n");
        }
        else
        {
            pc.PDALoginTerminate -= new PendingCommands.PDALoginTerminateEventHandler( DeinitLoginDialogs );
            SSCS.ActiveBackgroundThreads.Replace("DeinitLoginDialogs\r\n", "");
        }
    . . .

...and I finally (once I get to the last spot in the code before the hang) write the StringBuilder contents out to a text file, or try to:

StreamWriter file = new StreamWriter(@"\hereIAm.txt");
file.WriteLine(SSCS.ActiveBackgroundThreads.ToString());

...Yet, when I open that file (it does get created), it's got nothing in it (0 bytes). I know some of those InitializeBackgroundThread_* methods are getting called; it is possible that every one started also gets stopped prior to the file being written, but I highly doubt that...


Solution

  • Either Close() the stream writer or (better) put it into a using statement.

    using(StreamWriter file = new StreamWriter(@"\hereIAm.txt"))
    {
        file.WriteLine(SSCS.ActiveBackgroundThreads.ToString());
    }