I’m trying to create a C# console application that will generate a log file. I’d like to have some flexibility with where the log file will be stored.
I tried using the Settings.settings file with:
Name: logDrive Type: string Scope: Application Value: C:\Scripts\Logs
In my code, I’m using:
string logFile = DateTime.Now.ToShortDateString() + ' ' + DateTime.Now.ToShortTimeString(); logFile = logFile.Replace(@'/', @'-').Replace(@'\', @'-') + '.log'; string logDrive = Properties.Settings.Default.logDrive; StreamWriter output = new StreamWriter(logDrive + logFile);
When compiling the above I get the error message ‘The given path’s format is not support.’
If it helps, the values for:
logDrive = ‘C:\Scripts\ServiceDesk\Logs’ logFile = ‘3-23-2009 1:20 PM.log’
Does anyone have any thoughts/ recommendations for a better approach and/ or what I’m doing wrong?
You can’t include a
:in a filename. A better approach might be to use a format like(e.g.
20090323_231245.log)This has the benefit of being easily sortable, and it doesn’t use any invalid characters.
You can get this using
Notes:
Also, as suggested in the comments, you should consider using
Path.Combineto combine your directory and filename. This will help mitigate issues with trailing path separators, etc.