c# - Creating file then setting timestamp without releasing file lock -
i know if there way create file , set last write time (and other timestamp information) without allowing process acquire lock file between these 2 operations.
the reason want fix issue antivirus acquires lock file after has been created , still has lock time file attributes being attempted set. code working sevenzipsharp (no longer maintained far can see).
code reproduces issue is:
var filepath = "test.txt"; using (var filestream = new filestream(filepath, filemode.create, fileaccess.readwrite)) { var bytes = encoding.ascii.getbytes("hello fail."); filestream.write(bytes, 0, bytes.length); var fileinfo = new fileinfo(filepath); fileinfo.creationtime = datetime.now; }
this produces following exception when executing last statement: system.io.ioexception "the process cannot access file 'c:\test.txt' because being used process."
i considering implementing setting of time attributes retry mechanism, wondered if there more elegant solution.
as @damien_the_unbeliever mentioned, need file handle. try this.
class program { [dllimport("kernel32.dll", setlasterror = true)] [return: marshalas(unmanagedtype.bool)] static extern bool setfiletime(safefilehandle hfile, ref long lpcreationtime, ref long lplastaccesstime, ref long lplastwritetime); static void main(string[] args) { var filepath = "test.txt"; long when = datetime.now.adddays(10).tofiletime(); using (var filestream = new filestream(filepath, filemode.create, fileaccess.readwrite)) { if (!setfiletime(filestream.safefilehandle, ref when, ref when, ref when)) { throw new win32exception(); } var bytes = encoding.ascii.getbytes("hello fail."); filestream.write(bytes, 0, bytes.length); } } }
Comments
Post a Comment