Mark Mark - 1 year ago 214
C# Question

Append TimeStamp to a File Name

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# is by adding a time stamp to the file name with something like this

DateTime.Now.ToString().Replace('/', '-').Replace(':', '.')
Is there a better way to do this?

Answer Source

You can use DateTime.ToString Method (String)


or string.Format


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


string result = "myfile.txt".AppendTimeStamp();

Extension method

public static class MyExtensions
    public static string AppendTimeStamp(this string fileName)
        return string.Concat(
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download