C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: You can use DateTime formatting for filenames. A format string is provided.
DateTimeDateTime FormatC# 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
Part A: This format string has 3 placeholders: first, directory name we get from SpecialFolder, the separator char, and the specially formatted DateTime.
Also: The code specifies that the file name starts with text and ends with ".bin".
Part B: It gets the My Documents folder path. This line uses the SpecialFolder.MyDocuments enum value to get the path.
EnvironmentPart C: The code uses Path.DirectorySeparatorChar. On Windows, this is the backslash. You could just use \\ in the string instead.
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
Note: Filenames cannot have some characters. This is explored further in a separate article.
Reserved FilenamesTip: If you have to write files frequently, using the "ss" field can help—this writes seconds.