How to touch a file in C#?
Asked Answered
S

4

75

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?

Sile answered 11/11, 2009 at 16:43 Comment(2)
Couldn't you just open the file and save the file?Gilson
@Anish, That sounds like not the simplest, safest, or fastest way to do that... (imagine if the code crashed in the middle of rewriting the file, or if the file was >= a couple of hundred megs in size...)Storz
S
94
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)
Sile answered 11/11, 2009 at 16:44 Comment(4)
Unfortunately, this will not create a file that doesn't already exist.Riggins
@EdwardNedHarvey it's not a problem at all: if(!System.IO.File.Exists(fileName)) System.IO.File.Create(fileName); System.IO.File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);Transpire
@coirius FYI... You'll want to make sure to close the stream created by File.Create.Turk
There's a race condition that can occur between the 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
R
8

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);
}
Riggins answered 4/7, 2013 at 17:5 Comment(0)
T
1

The easiest way is using FileInfo:

var fi = new FileInfo(file);
fi.LastWriteTime = DateTime.Now;
Talon answered 31/1 at 2:18 Comment(0)
A
-2

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

Anishaaniso answered 12/3, 2011 at 0:2 Comment(1)
You should never put something in %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.