user3281950
user3281950

Reputation: 143

DateTime as file name

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?

Upvotes: 2

Views: 6099

Answers (3)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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");

Upvotes: 2

Ruben de la Fuente
Ruben de la Fuente

Reputation: 695

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

DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");

Upvotes: 11

TonySB
TonySB

Reputation: 13

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

Upvotes: 0

Related Questions