开发者

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 da开发者_JAVA百科te) 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)


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜