c# - SetFileTime returning error code 5 -
i trying p/invoke setfiletime, can't seem work. returns error code of 5 me (access denied), , not sure why. here code using:
void main() { var pointer = createfile(@"c:\users\user\desktop\new folder\new text document.txt", fileaccess.readwrite, fileshare.none, intptr.zero, filemode.open, fileattributes.normal, intptr.zero); console.writeline(pointer); var = datetime.now.tofiletime(); long lpcreationtime = now; long lplastaccesstime = now; long lplastwritetime = now; if (!setfiletime(pointer, ref lpcreationtime, ref lplastaccesstime, ref lplastwritetime)) console.writeline(getlasterror()); closehandle(pointer); } [dllimport("kernel32.dll")] static extern uint32 getlasterror(); [dllimport("kernel32.dll", setlasterror = true)] static extern boolean setfiletime(intptr hfile, ref long lpcreationtime, ref long lplastaccesstime, ref long lplastwritetime); [dllimport("kernel32.dll", setlasterror = true)] static extern boolean closehandle(intptr hobject); [dllimport("kernel32.dll", charset = charset.unicode, setlasterror = true)] static extern intptr createfile(string filename, [marshalas(unmanagedtype.u4)] fileaccess fileaccess, [marshalas(unmanagedtype.u4)] fileshare fileshare, intptr securityattributes, [marshalas(unmanagedtype.u4)] filemode creationdisposition, [marshalas(unmanagedtype.u4)] fileattributes flags, intptr template);
my pointer valid (2376) see setfiletime has failed , has returned error code of 5 (access denied). now, have ensured running administrator , account has permissions path, still, no cigar. have ideas why happening?
update
marshal.getlastwin32error()
returns 5 after call setfiletime
. also, need making call work can setfiletime
on long paths in windows, createfile
supports, current file libraries of .net not support long paths in windows.
from documentation of setfiletime
:
a handle file or directory. handle must have been created using createfile function file_write_attributes access right.
your code doesn't manage that. .net fileaccess
enumeration not compatible win32 access flags. you'll need define enum use createfile
. likewise use of fileshare
, filemode
not correct.
this p/invoke declaration should suffice: http://www.pinvoke.net/default.aspx/kernel32.createfile
as alexei said, don't call getlasterror
because may picking error code framework call rather true error. use setlasterror = true
, marshal.getlastwin32error()
.
you fail check errors in return value if createfile
.
Comments
Post a Comment