kalle31
kalle31

Reputation: 11

Use date as a filepath

I need the following filepath according to date:

yyyy\MM\d

and I though I could it in one call to DateTime class like this:

string filepath = DateTime.Now.ToString(@"yyyy\MM\d");

However, it yields: "2018M11d" which is wrong.

Is there a way to escape the backwards slahes?

Upvotes: 0

Views: 110

Answers (3)

Pratik Rathi
Pratik Rathi

Reputation: 86

You can do this:

DateTime.Now.ToShortDateString();

This will help you.

Upvotes: -1

Konamiman
Konamiman

Reputation: 50323

The safest way is to split the date in its individual components and then use Path.Combine:

var dateParts = DateTime.Now.ToString("yyyy MM d").Split(' ');
var filePath = Path.Combine(dateParts);

This isolates you from the underlying filesystem details you aren't really concerned about (i.e. which character is used as the directory separator).

Upvotes: 4

mb14
mb14

Reputation: 452

Yes. You can.

string filepath = DateTime.Now.ToString(@"yyyy\\MM\\d");

Upvotes: 4

Related Questions