You can use DateTime.ToString Method (String)
DateTime.Now.ToString("yyyyMMddHHmmssfff")
or string.Format
string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now)
;
or Interpolated Strings
$"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"
There are following custom format specifiers y (year), M (month), d
(day), h (hour 12), H (hour 24), m (minute), s (second), f (second
fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or
A.M) and z (time zone).
With Extension Method
Usage:
string result = "myfile.txt".AppendTimeStamp();
//myfile20130604234625642.txt
Extension method
public static class MyExtensions
{
public static string AppendTimeStamp(this string fileName)
{
return string.Concat(
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("yyyyMMddHHmmssfff"),
Path.GetExtension(fileName)
);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…