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?
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
you can use:
Stopwatch.GetTimestamp();
Perhaps appending DateTime.Now.Ticks
instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.
You can use below instead:
DateTime.Now.Ticks
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
Source: Stackoverflow.com