views:

1723

answers:

2

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?

+13  A: 

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.

Daniel LeCheminant
+1. I name my log files in a similar way so they can be sorted.
Brian Ensink
You should also be using System.IO.Path.Combine(logDrive, logFile) instead of manually concatenating them ;)
womp
+1 here to... DateTime.Now.ToString("yyyymmdd_hhMMss")
Tracker1
@Tracker1: I think you'v reversed minutes and the month
Daniel LeCheminant
@ck, @Daniel L Thank you, I ended up using: string logFile = DateTime.Now.ToString("yyyyMMdd_HHmmss");
Zambian
@womp Thank you for the System.IO.Path.Combine tip. I had not heard of this, so did some reading and have started using it. If anyone else cares, check out http://mattberseth.com/blog/2007/04/systemiopath.html
Zambian
A: 

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

Nick
Thank you for catching this. I added the trailing slash.
Zambian