Append TimeStamp to a File Name

后端 未结 6 785
清歌不尽
清歌不尽 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:36

    For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            //
            // Write file containing the date with BIN extension
            //
            string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
                DateTime.Now);
            File.WriteAllText(n, "abc");
        }
    }
    

    Output :

    C:\Users\Fez\Documents\text-2020-01-08_05-23-13-PM.bin
    

    "text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"

    text- The first part of the output required Files will all start with text-

    {0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here

    yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem

    MM- Prints the month in two digits

    dd_ Prints the day in two digits followed by an underscore

    hh- Prints the hour in two digits

    mm- Prints the minute, also in two digits

    ss- As expected, it prints the seconds

    tt Prints AM or PM depending on the time of day

    | |

提交回复
热议问题