windows - Delphi: Creating and Reading a text file is causing an I/O 32 error. Should this be prevented using sleep? -
i working on program needs able report whether or not windows has been activated.
function tsoftwarereport.getlicenceinfo : string; var activated : string; licencefile : textfile; begin // redirect command output txt file shellexecute(0,nil,'cmd.exe', '/c cscript %windir%\system32\slmgr.vbs/xpr > c:\activated.txt', nil, sw_hide); //read file sleep(1000); assignfile(licencefile, 'c:\activated.txt'); reset(licencefile); while not eof(licencefile) begin readln(licencefile,activated); if ansicontainstext(activated, 'permanently') begin activated := 'permanent'; break; end; end; //cleanup file closefile(licencefile); deldir('c:\activated.txt'); result := activated; end; currently using shellexecute , redirecting output text file, want read in order find out if windows has been activated.
the problem having when go shellexecute line followed assignfile line i/o 32 error. suspect due shellexecute not closing file before attempt access "assignfile". why have sleep() line in. problem don't know how long should sleeping performance different across machines.
i tried writing code try running assignfile line , if fails, sleep() , try again i'm throwing exceptions on purpose. whole thing feels hacky , badly written. feel bad having redirect output shellexecute text file.
so question is, should using sleep, , if how decide how long sleep for? should using alternative?
should using sleep?
no.
should using alternative?
yes. use wait function block until process created has terminated. read output file.
there few options affect design choices.
in order wait, need obtain process handle. can shellexecuteex or createprocess. not shellexecute.
if wish redirect output, , don't want code redirection yourself, need continue using cmd.exe , getting perform redirection. alternatively can use createprocess , supply either file handle or pipe handle new process stdout handle.
if avoid creating file going used transient output. pipes made for. create pipe , feed write end new process stdout of new process. read contents out of read end of pipe. way avoid spewing files file system. what's more allows avoid spawning cmd.exe process not need.
one final point make don't check errors when calling shellexecute. granted, shellexecute doesn't report errors well, must learn check errors when calling api functions. if functions fail, , don't check errors, how can expect diagnose went wrong?
Comments
Post a Comment