2

I need to create some log files with a name like this: HH:mm_dd-MM-yyyy.log

I've tried to convert DateTime & DateTime.Now like this but the compiler encounters the next error:

The given path's format is not supported.

Code i've tried:

#1
var currentDateTime = DateTime.Now;
string format = "HH:mm_dd-MM-yyyy";
string datetime = currentDateTime.ToString(format);
File.Create("Log/GameLog/"+datetime+".log");
#2
string datetime = DateTime.Now.ToString("HH:mm_dd-MM-yyyy");
File.Create("Log/GameLog/"+datetime+".log");

In this couple of cases the same error was raised by the compiler... So in the end, my question is, how can i use datetime as a file name?

user3281950
  • 143
  • 1
  • 4
  • 12
  • 2
    and btw, if you want all the log files to be order by date, use `DateTime.Now.ToString("yyyyMMddHHmmss")` then all files from the same day will be always stick together – balexandre Mar 09 '14 at 15:49

3 Answers3

11

The problem is the : character, you can't use that in a file name

DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
Oli B
  • 514
  • 5
  • 17
Ruben de la Fuente
  • 695
  • 11
  • 23
2

Widows Operating System does not allow following special characters in filename.

/ \ : * ? " < > |

so you need to Replace colon : with some other character (either with _ or with -)

Try This:

string datetime = DateTime.Now.ToString("HH_mm_dd-MM-yyyy");
CDspace
  • 2,639
  • 18
  • 30
  • 36
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
0

try removing some of the characters you are returning with format and then add them in on at a time to see which is causing the problem.

My guess is it maybe the : character causing you a problem

also check this post which may help.

How to remove illegal characters from path and filenames?

regards

Community
  • 1
  • 1
TonySB
  • 13
  • 4