Question

I wrote a piece of code in c# to get the date of creation of a text file and to have the date in yyyyMMddHHMMSS format :

FileInfo fileInfo = new FileInfo("test.txt");
DateTime fileCreatedDate = fileInfo.CreationTime;
string dateCreation = fileCreatedDate.ToString("yyyyMMddHHMMSS");

But it didn't work, dateCreation is for example: 201401291001SS

How can I modify it ?

Was it helpful?

Solution

You have uppercase minutes which are months, use mm (and ss) instead:

string dateCreation = fileCreatedDate.ToString("yyyyMMddHHmmss");

OTHER TIPS

Look at this line:

FileInfo fileInfo = new FileInfo("test.txt");

I think you forget to add your path. Refer to below example:

 string path = @"yourpath\test.txt";
 FileInfo fileInfo = new FileInfo(path);

And then:

string dateCreation = fileCreatedDate.ToString("yyyyMMddHHmmss");

Try this

MM refers two digit month

mm refers two digit minutes

FileInfo fileInfo = new FileInfo("test.txt");
DateTime fileCreatedDate = fileInfo.CreationTime;
string dateCreation = fileCreatedDate.ToString("yyyyMMddHHmmss");
//Take a file 
DateTime creationTime = File.GetCreationTime(@"C:\CC.txt");
//Print
Response.Write(creationTime.ToString("yyyyMMddHHmmss")); 
FileInfo fileInfo = new FileInfo("test.txt");
DateTime fileCreatedDate = fileInfo.CreationTime;
string date = fileCreatedDate.ToString("yyyyMMddHHmmss");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top