How to touch a file in C#?

后端 未结 3 1187
庸人自扰
庸人自扰 2020-12-29 17:55

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 th

相关标签:
3条回答
  • 2020-12-29 18:06

    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 讨论(0)
  • 2020-12-29 18:14
    System.IO.File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);
    
    0 讨论(0)
  • 2020-12-29 18:32

    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);
    }
    
    0 讨论(0)
提交回复
热议问题