John
John

Reputation: 3945

save todays date to file name

Trying to include date into a filename when the file is written.

DateTime todaysDate = DateTime.Now;
string destFile = System.IO.Path.Combine(targetPath + todaysDate.ToShortDateString() + ".dat");

Error:

 Could not find a part of the path 'C:\Users\John\Desktop\Sales\Import11/02/2014.dat'.

Possible to change date to separated by _ ? or any other suggestions to resolve this? Ta

Upvotes: 0

Views: 1836

Answers (6)

Jon Skeet
Jon Skeet

Reputation: 1500755

I would suggest:

  • Using a sortable date format, just because that's naturally pleasant
  • Explicitly specifying the invariant culture, to avoid oddities of ending up using a different calendar system. (I suspect you always want to use the Gregorian calendar.)
  • Explicitly specifying delimiters which aren't going to cause problems in a file system path (which / and : do)

So something like:

string name = string.Format(CultureInfo.InvariantCulture,
                            "Import-{0:yyyy-MM-dd}.dat",
                            DateTime.Today);

// Assuming that targetPath is the directory; it's slightly unclear.
string path = Path.Combine(targetPath, name);

Note:

  • By using Today, you're using the system local time zone. That may well be what you want, but you need to consider it explicitly.
  • You're only using the date, rather than the date and time - is that definitely okay? Will you ever need to handle multiple imports on the same day?

Upvotes: 0

Victor Sigler
Victor Sigler

Reputation: 23451

You could try this :

var title = String.Format("NameOfYOuWant {0}.log", DateTime.Today.ToShortDateString().Replace('/', '-'))

Upvotes: 0

Kaspars Ozols
Kaspars Ozols

Reputation: 7017

Use this:

DateTime todaysDate = DateTime.Now;
string destFile = string.Format("{0}{1:yyyy_MM_dd}.dat" , targetPath, todaysDate);

Upvotes: 0

Jason Evans
Jason Evans

Reputation: 29186

Try using another delimiter, such as underscore _

todaysDate.ToString("dd_MM_yyyy_HH_mm_ss");

/ is not a valid character for a file path. You can use various other characters, as long as they are not illegal for a file path.

This MSDN reference should help.

http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx

Upvotes: 0

TyCobb
TyCobb

Reputation: 9089

You need to format the date so it doesn't have illegal or unwanted characters.

System.IO.Path.Combine(targetPath + todaysDate.ToString("yyyy.MM.dd_HHmmss") + ".dat");

Here is a list of all of the format options for Date and Time.

Upvotes: 1

James
James

Reputation: 82096

It's best to format the date in a way which you know it won't conflict with the file path, an underscore _ or a - or no separator at all are better alternatives

string destFile = Path.Combine(targetPath, 
    String.Format("{0}.dat", todaysDate.ToString("dd-MM-yyyy")));

Upvotes: 4

Related Questions