In C#, what's the simplest/safest/shortest way to make a file appear as though it has been modified (i.e. change its last modified date) without changing the contents of the file?
System.IO.File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);
If you don't know whether the file exists, you can use this:
if(!System.IO.File.Exists(fileName))
System.IO.File.Create(fileName).Close(); // close immediately
System.IO.File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow)
File.Exists
check and the File.Create
, where a file could be created in the meantime, in which case the file will be overwritten. –
Timoteo This works. Could throw DirectoryNotFoundException, and various other exceptions thrown by File.Open()
public void Touch(string fileName)
{
FileStream myFileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
myFileStream.Dispose();
File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);
}
The easiest way is using FileInfo
:
var fi = new FileInfo(file);
fi.LastWriteTime = DateTime.Now;
Your solution with System.IO.File.SetLastWriteTimeUtc
will not let you touch the file, if the file is in use. A "hacky" way to touch a file that is in use would be to create your own touch.bat (since Windows doesn't have one like Linux does) and drop it to \windows\system32, so that you can invoke it from anywhere without specifying a full path.
The content of the touch.bat would then be (probably you can do it better without a temp file, this worked for me):
type nul > nothing.txt
copy /B /Y nothing.txt+%1% > nul
copy /B /Y nothing.txt %1% > nul
del nothing.txt
EDIT: The following property can be set on a locked file: new FileInfo(filePath).LastWriteTime
%windir%\system32
. Instead you should modify your PATH
environment variable to include the path where you put it. –
Cover © 2022 - 2024 — McMap. All rights reserved.