I am using the following code to write the Date Modified time of a Directory to a label
string selectedPath = comboBox1.SelectedItem.ToString();
DateTime las
In .NET CORE
You will need to get the absolute path of the file.
Add reference to Microsoft.Extensions.Hosting
Inject that into your constructor
The ContentRootPath
property will be your web root.
Grab your server path
var Files = FIO.Directory.GetFiles("Unzipped");
This will be your actual path
var Path = string.Format(@"{0}\{1}",WebRootPath, Files[0]);
var CreationDate = File.GetLastWriteTime(Path);
From the documentation:
If the directory described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.
So presumably your time zone is UTC-5 (in January), and the directory doesn't exist...
first thought is that of is your time set correctly. Second thought is to right click on that folder and see what it says in properties. Lastly I'd make new test folder and run that bit of GetLastWriteTime tests on it so you know what you are getting back.
GetLastWriteTime
not always return reliable date time, use this
string selectedPath = comboBox1.SelectedItem.ToString();
DateTime now = DateTime.Now;
TimeSpan localOffset = now - now.ToUniversalTime();
DateTime lastdate = File.GetLastWriteTimeUtc(selectedPath) + localOffset;
datemodified.Text = lastdate.ToString();
An easy way to test for file not found with the result of GetLastWriteTime()
/GetLastWriteTimeUtc()
without hardcoding the sentinel epoch date/times that are used to indicate a file/dir not found condition, is as follows:
// ##### Local file time version #####
DateTime fileTimeEpochLocal=DateTime.FromFileTime(0);
// Use File.GetLastWriteTime(pathname) for files
// and Directory.GetLastWriteTime(pathname) for directories
DateTime lastWriteTime=Directory.GetLastWriteTime(selectedPath);
// Check for a valid last write time
if (lastWriteTime!=fileTimeEpochLocal) // File found
DoSomethingWith(selectedPath,lastWriteTime);
else // File not found
HandleFileNotFound(selectedPath);
// ##### UTC file time version #####
DateTime fileTimeEpochUtc=DateTime.FromFileTimeUtc(0);
// Use File.GetLastWriteTimeUtc(pathname) for files
// and Directory.GetLastWriteTimeUtc(pathname) for directories
DateTime lastWriteTimeUtc=Directory.GetLastWriteTimeUtc(selectedPath);
// Check for a valid last write time
if (lastWriteTimeUtc!=fileTimeEpochUtc) // File found
DoSomethingWith(selectedPath,lastWriteTimeUtc);
else // File not found
HandleFileNotFound(selectedPath);
Old question, but today I faced this issue. That particular date is also returned when your path is invalid or the file doesn't exists, because there is no built in exception in any of those cases.