Reputation: 71
I want to create a Filename with DateTime.Now to store the errors that catched using Exception Handling everyday.
I used DateTime.ToFileTime
, but the format appending for not in date format.
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToFileTime()+ ".txt";
FileStream fi = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw1 = new StreamWriter(fi);
sw1.WriteLine(DateTime.Now + "" + ex.message);
I am Expecting the filename like "ErrorCollector17/08/2019"
Upvotes: 1
Views: 3489
Reputation: 46249
You can try to use ToString
function with a format.
DateTime.Now.ToString("dd/MM/yyyy",new System.Globalization.CultureInfo("en-US"));
As Soundararajan say I would suggest you use
"ddMMyyyy"
or
"dd-MM-yyyy"
due to the system will confuse your path contain \
Upvotes: 2
Reputation: 578
shortest answer would be the code below:
DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
DateTime.Now
gets the current date and time based on your computer's clock.
.ToString(...)
converts the DateTime object into a string with optional formatting inside as parameters.
"yyyyMMddHHmmss"
is a pattern for how you want the DateTime object be mapped in a string manner where. assuming your computer's clock is currently ticked at "August 8, 2019 12:34:56 PM", then:
and the output would be 20190808123456
. Note that the arrangement of year, month, date, hour, minute, or even second can be in no specific order.
CultureInfo.InvariantCulture
is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings (via source)
note that we removed special characters separating different parts of the DateTime object to prevent issues when filenames on Windows.
Upvotes: 1
Reputation: 56
You are not allowed to create filename which contains any of following characters: /:*?"<>| on Windows, you can do like this
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToString("dd-MM-yyyy")+ ".txt"
Upvotes: 3