小编use*_*376的帖子

修改WriteLine方法的行为?

我需要一个非常简单的想象的东西 - 修改System.Console类方法WriteLine不仅可以写入控制台,还可以写入文本日志文件。

我只需要在调用 WriteLine 之前使用预设参数运行此函数,然后执行通用 WriteLine:

class Logger
{
    static public void WriteLog(string logMessage, string fileName ,bool addTimeStamp = true)
    {
        //Getting temp folder
        string destPath = Path.GetTempPath();

        //Creating folder
        if (!Directory.Exists(destPath))
            Directory.CreateDirectory(destPath);

        //Naming log file
        var filePath = String.Format("{0}\\{1}.log",
            destPath,
            fileName
            );

        //Writing to timestamp
        if (addTimeStamp)
        {
            logMessage = String.Format("[{0}] - {1}{2}",
                DateTime.Now.ToString("HH:mm:ss", CultureInfo.CurrentCulture),
                logMessage,
                Environment.NewLine);
        }
        else
        {
            logMessage = String.Format("{0}{1}",
                logMessage,
                Environment.NewLine);
        }
        //Writing to log
        File.AppendAllText(filePath, logMessage);
    }
}
Run Code Online (Sandbox Code Playgroud)

我考虑过继承,但我什至无法创建一个类,因为 …

c# console-application static-classes

1
推荐指数
1
解决办法
106
查看次数

标签 统计

c# ×1

console-application ×1

static-classes ×1