I'm appending text to an existing TXT file and one of the fields I'm recording the date and time, which are passed to a StreamWriter. The issue I'm having is that using the script a few times in a row is causing the record to come up with the same date and time.
Below is a snippet of what I'm getting as a result and my class just below. Any help would be very much appreciated.
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();
}
}
}
CodePudding user response:
You're using the global variable datetime
. This value is set once time when your application started.
fileAppend.WriteLine($"{dateTime}, {userName}, {scriptName}, {path}, {timeSavings}");
You should update it to
fileAppend.WriteLine($"{DateTime.Now}, {userName}, {scriptName}, {path}, {timeSavings}");
CodePudding user response:
In your question, you shared output
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
Please look into 8:42:54 PM
, log is written in one second, please logged time with nanoseconds second like this DateTime.Now " " DateTime.Ticks
.
I hope, it will be resolved your issue.