![](/img/trans.png)
[英]download the file from the navigation link from the website by logging in from Console application C#
[英]C# server logging to text file from console
我目前有一个与localhost上的服务器通信的客户端。 当客户端与服务器通信时,服务器会跟踪正在发生的事情,例如。
string response = "Location updated for " + uname + ": " + uloc;
Console.WriteLine(response);
我试图通过将其写到在“公共类”中声明的文本文件中来记录服务器控制台列出的所有内容。
public static System.IO.StreamWriter serverlog = new System.IO.StreamWriter("serverlog.txt", true);
我尝试将写入行添加到txt文件,如下所示。
string response = "Location updated for: " + commands[0];
Console.WriteLine(response);
serverlog.WriteLine("[" + DateTime.Now.ToString("h:mm:ss tt") + "] [Server]: " + response);
serverlog.close();
但是,当我尝试在serverlog.close();
之后再次写入serverlog.txt时serverlog.close();
如果执行该命令,则会完全破坏该程序,除非从Visual Studio重新运行该程序,否则无法再次执行从客户端到服务器的命令。 如何再次打开流编写器,以便可以在服务器仍在运行时附加到文本文件?
让我知道是否需要更多代码。
提前致谢。
编辑:
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);
关闭serverlog
对象后,每次要使用它时都必须重新打开它。 而不是一团糟,只需使用File
类:
System.IO.File.AppendAllText(filepath, "text to write");
那将在内部处理所有的streamwriting等。 无需实例化,也无需关闭。
我建议您创建一种具有writeToLog(String)
方法的日志记录类。 在该方法内部,您可以写入控制台,日志文件以及所需的任何其他位置,而不必每次都明确地进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.