How to touch a file in C#?

C#.NetFile

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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)

Solution 2 - C#

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.Close();
    myFileStream.Dispose();
    File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);
}

Solution 3 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt HowellsView Question on Stackoverflow
Solution 1 - C#Matt HowellsView Answer on Stackoverflow
Solution 2 - C#Edward Ned HarveyView Answer on Stackoverflow
Solution 3 - C#katerohView Answer on Stackoverflow