How does DateTime.Now.Ticks exactly work?
In my application I generate files at random opportunities. To ensure a unique naming, I tried to use the nano seconds since 1.1.1970:
long time = DateTime.Now.Ticks;
String fileName = Convert.ToString(time);
Console.WriteLine(fileName);
Now I observed something weird. Why is the output like that? I mean why are the last 4 numbers always the same? I can use this as a filename, that is not the problem, but I'm just wondering about it.
634292263478068039
634292263512888039
634292263541368039
634292263603448039
634292263680078039
Solution 1:
The resolution of DateTime.Now
depends on your system timer (~10ms on a current Windows OS)...so it's giving the same ending value there (it doesn't count any more finite than that).
Solution 2:
Not really an answer to your question as asked, but thought I'd chip in about your general objective.
There already is a method to generate random file names in .NET.
See System.Path.GetTempFileName and GetRandomFileName.
Alternatively, it is a common practice to use a GUID to name random files.
Solution 3:
You can get the milliseconds since 1/1/1970 using such code:
private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}
Solution 4:
to convert the current datetime to file name to save files you can use
DateTime.Now.ToFileTime();
this should resolve your objective