DateTime.Now 连续多次返回同一时间

DateTime.Now returning the same time several times in a row

我将文本附加到现有的 TXT 文件和我正在记录日期和时间的字段之一,这些字段将传递给 StreamWriter。我遇到的问题是连续多次使用该脚本会导致记录出现相同的日期和时间。

下面是我得到的结果的片段,下面是我的 class。非常感谢任何帮助。

14/09/2021 8:42:54 PM, nflab, ScriptName, C:\Documents\filename.rvt, 1500
14/09/2021 8:42:54 PM, nflab, ScriptName, C:\Documents\filename.rvt, 1500
14/09/2021 8:42:54 PM, nflab, ScriptName, C:\Documents\filename.rvt, 1500
14/09/2021 8:42:54 PM, nflab, ScriptName, C:\Documents\filename.rvt, 1500
14/09/2021 9:08:21 PM, nflab, ScriptName, C:\Documents\filename.rvt, 1500
14/09/2021 9:08:21 PM, nflab, ScriptName, C:\Documents\filename.rvt, 1500

public static class Usage
{
    readonly static DateTime dateTime = DateTime.Now;
    readonly static string filename = "ScriptUsageLog_";
    readonly static string userName = System.Environment.UserName;
    readonly static string fileExtension = ".txt";
    static string path;

    public static void Log(Document doc, string scriptName, int timeSavings = 0)
    {
        path = doc.PathName;

        using (StreamWriter fileAppend = File.AppendText(FileLocations.UsageFolder +
                                                                       filename +
                                                                       userName +
                                                                       fileExtension))
        {
            fileAppend.WriteLine($"{dateTime}, {userName}, {scriptName}, {path}, {timeSavings}");
            fileAppend.Close();
        }
    }
}

您正在使用全局变量 datetime。该值在您的应用程序启动时设置一次。

fileAppend.WriteLine($"{dateTime}, {userName}, {scriptName}, {path}, {timeSavings}");

你应该更新到

fileAppend.WriteLine($"{DateTime.Now}, {userName}, {scriptName}, {path}, {timeSavings}");