mayumi Tai
mayumi Tai

Reputation: 55

Path format is illegal

I want to ask about a easy question , but I faced a problem. I want to get the time when the program is executed

Console.WriteLine(DateTime.Now);

And I want to output a .log file , the file name will have program execution time

String path2 = "C:\\temp"+DateTime.Now+".log";
StreamWriter path = File.CreateText(path2);
path.WriteLine(DateTime.Now);

But it is telling me Path format is illegal.

And I want ask another question

string a12 = aaa.Element("a12").tostring();
String path2 = "C:\\temp" + a12.ToString + ".log";

But it tell me "Path format is illegal"

How can I resolve it?

Thanks

Upvotes: 0

Views: 161

Answers (5)

Maku
Maku

Reputation: 1558

That's because DateTime.Now converted to string by default contains time information (e.g. 8:53). Semicolon is illegal in path name.

If you meant only date to be in your file name, you could use:

String path2 = "C:\\temp" + DateTime.Now.ToString("d") + ".log";

(Edit) For some cultures this still can lead to invalid values, so as others pointed out, it is best to use explicit formatter:

String path2 = "C:\\temp" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

Upvotes: 2

Amit
Amit

Reputation: 33

String path2 = String.Format("C:\\temp{0}.log", DateTime.Now.ToString("yyyyMMdd"));

Since filename cannot take "/" which was created by DateTime.Now.ToString("d") and hence creating issue.

Upvotes: 1

Dirk Trilsbeek
Dirk Trilsbeek

Reputation: 6023

DateTime.Now probably contains illegal characters depending on your local system settings. To get a valid and consistent file name independent on the culture the system is installed in you should create the log file name by hand, for instance like this:

String path2 = "C:\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156978

When you put DateTime.Now into a path, you risk adding characters that aren't valid as a path (like the : separator. That is the reason you get this error message.

You could replace it with a .:

string path2 = Path.Combine
               ( @"C:\temp\"
               , DateTime.Now.ToString("yyyy-MM-dd.HH24.mm.ss")
               , ".log"
               );

Upvotes: 1

BadZen
BadZen

Reputation: 4265

You want to escape your \ in the "" quoted string, and also there are characters in the result of DateTime.Now that cannot be in paths. You'll need to escape/replace those as well.

Upvotes: 1

Related Questions