Aotik
Aotik

Reputation: 348

C# server logging to text file from console

I currently have a client which is communicating with a server on localhost. When the client communicates with the server, the server keeps track of what is happening, eg.

string response = "Location updated for " + uname + ": " + uloc;
Console.WriteLine(response);

I am trying to keep a log of whatever the server console is listing by writing it out to the text file declared like so in the "public class".

public static System.IO.StreamWriter serverlog = new System.IO.StreamWriter("serverlog.txt", true);

I tried adding a writeline to the txt file as shown below.

 string response = "Location updated for: " + commands[0];
 Console.WriteLine(response);
 serverlog.WriteLine("[" + DateTime.Now.ToString("h:mm:ss tt") + "] [Server]: " + response);
 serverlog.close();

However, when I try to write to serverlog.txt again after serverlog.close(); is executed, it completely screws up the program, and no command from client to server can be executed again unless the program is re-run from Visual Studio. How do I re open the streamwriter again so I can append to the text file while the server is still running?

Let me know if more of my code is needed.

Thanks in advance.

EDIT:

static void WriteToLog(string logtext)
    {
        System.IO.File.AppendAllText("nserverlog.txt", string.Format("{0}{1}", logtext, Environment.NewLine));
    }


WriteToLog("[" + DateTime.Now.ToString("h:mm:ss tt") + "] [Server]: " + response);

Upvotes: 0

Views: 1471

Answers (1)

Russell Uhl
Russell Uhl

Reputation: 4531

Once you close the serverlog object, you have to re-open it every time you want to use it. Rather than go through that whole mess, just use the File class:

System.IO.File.AppendAllText(filepath, "text to write");

That will handle all the streamwriting etc. internally. Nothing to instantiate, nothing to close.

I suggest you create some sort of logging class that has a writeToLog(String) method. Inside that method, you could write to the console and to the log file and to anywhere else you want, rather than explicitly doing both every time.

Upvotes: 1

Related Questions