Ashwin Kumar
Ashwin Kumar

Reputation: 71

How to Create a Text Filename with DateTime using C#

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

Answers (3)

D-Shih
D-Shih

Reputation: 46249

You can try to use ToString function with a format.

 DateTime.Now.ToString("dd/MM/yyyy",new System.Globalization.CultureInfo("en-US"));

c# online

As Soundararajan say I would suggest you use

"ddMMyyyy"

or

"dd-MM-yyyy"

due to the system will confuse your path contain \

Upvotes: 2

Nii
Nii

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:

  • yyyy = is a 4 digit year as 2019
  • MM = is a 2 digit month equivalent such as 08
  • dd = is a 2 digit day of the year such as 08
  • HH = is a 2 digit hour equivalent in 24 Hours format such as 12
  • mm = is a 2 digit minute such as 34
  • ss = is a 2 digit second such as 56

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

Sonduong
Sonduong

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

Related Questions