How to touch a file in C#?

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?


Solution 1:

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:

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);
}