Storing File Path as variable for C# Console Application
-
21-08-2019 - |
Question
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?
Solution
You can't include a :
in a filename. A better approach might be to use a format like
YYYYMMDD_HHMMSS.log
(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
string logFile = string.Format("{0:yyyyMMdd_HHmmss}.log", DateTime.Now);
Notes:
Also, as suggested in the comments, you should consider using Path.Combine
to combine your directory and filename. This will help mitigate issues with trailing path separators, etc.
OTHER TIPS
You'll also need to add a trailing slash to your 'logDrive'. I.e:
logDrive = "C:\Scripts\ServiceDesk\Logs\"
..or use Path.Combine as suggested in the other answer