Append TimeStamp to a File Name

后端 未结 6 779
清歌不尽
清歌不尽 2020-12-07 16:57

I have come across this problem several times in which I would like to have multiple versions of the same file in the same directory. The way I have been doing it using C# i

6条回答
  •  生来不讨喜
    2020-12-07 17:52

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

提交回复
热议问题