TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# DateTime for Filenames

These C# example programs demonstrate how to put a DateTime in filenames.

Filename, DateTime. A filename can store the date and time.

This clearly identifies the file in a unique way. There are many ways of accomplishing this. Some are clearer to read and easier to modify than others. We include the date, or the date and the time.

Tip: You can use DateTime formatting for filenames. A format string is provided.

Dates and required filenames

Date:              11/18/2014 5:04:44 PM
Required filename: text-2014-11-18_05-04-44-PM.bin

Date:              11/23/2004 12:05:47 AM
Required filename: text-2004-11-23-12_05-47-AM.bin

Example. We use the current date and time as the name for a file on the file system. We 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.

DateTime.Now

C# program that uses date as filename

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, "aaa");
    }
}

Description of format string

"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

Environment.SpecialFolder. You can use this code with Environment.SpecialFolder. You can encapsulate the logic for this in a property accessor. In other words, you can use a property to easily get the complete filename.

Property

C# program that uses filename property

using System;
using System.IO;

class Program
{
    static string SpecialFileName
    {
	get
	{
	    // A
	    return string.Format("{0}{1}text-{2:yyyy-MM-dd_hh-mm-ss-tt}.bin",
		// B
		Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
		// C
		Path.DirectorySeparatorChar,
		// D
		DateTime.Now);
	}
    }

    static void Main()
    {
	Console.WriteLine(SpecialFileName);
    }
}

Output

C:\Users\Sam\Documents\text-2008-11-18_05-23-13-PM.bin

This example uses a format string in part A. This format string has three placeholders: first, the directory name we get from SpecialFolder, then the separator char, and finally the specially formatted DateTime.

Also: The code specifies that the file name starts with text and ends with ".bin".

Next: It gets the My Documents folder path. This line uses the SpecialFolder.MyDocuments enum value to get the path.

Environment

Finally, it uses Path.DirectorySeparatorChar. On Windows, this is the backslash. You could just use \\ in the string instead. It uses DateTime.Now. As expected, this returns the local time.

Separators. You can change the string separators by replacing the underscores and dashes with any other character, excluding some special ones. I haven't found many uses for separators other than dashes, underscores, and spaces.

Note: Filenames cannot have some characters. This is explored further in a separate article.

Reserved Filenames

Summary. We generated file names containing the current date. This is useful for "data dumps" and log files where daily files are written. Never use random names except when you need temporary files. It is often better to append the date.

Tip: If you have to write files frequently, using the "ss" field can help—this writes seconds.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf