lundi 11 mai 2015

Delphi: Creating and Reading a text file is causing an I/O 32 error. Should this be prevented using sleep?

I am currently working on a program that needs to be able to report whether or not Windows has been activated.

function TSoftwareReport.getLicenceInfo : String;
var
  Activated : String;
  LicenceFile : TextFile;
begin
  // redirect command output to txt file
  ShellExecute(0,nil,'cmd.exe', '/C cscript %windir%\system32\slmgr.vbs/xpr > C:\Activated.txt', nil, SW_HIDE);
  //Read the file
  Sleep(1000);
  AssignFile(LicenceFile, 'C:\Activated.txt');
  Reset(LicenceFile);
  while not Eof(LicenceFile) do
  begin
    ReadLn(LicenceFile,Activated);
    if AnsiContainsText(Activated, 'Permanently') then
    begin
      Activated := 'Permanent';
      Break;
    end;
  end;
  //cleanup file
  CloseFile(LicenceFile);
  DelDir('C:\Activated.txt');
  Result := Activated;
end;

Currently I am using the ShellExecute and redirecting the output to a text file, that I then want to read in order to find out if Windows has been activated.

The problem I am having is that when I go to do the ShellExecute line followed by the AssignFile line I get an I/O 32 error. I suspect that this is due to ShellExecute not closing the file before I attempt to access it with "AssignFile". Which is why I now have the Sleep() line in. The problem with this is that I don't know how long I should be sleeping for as performance will be different across machines.

I tried writing code that would try running the AssignFile line and if that fails, then sleep() and try again but now I'm throwing exceptions on purpose. The whole thing just feels hacky and badly written. I already feel bad about having to redirect the output from shellexecute to a text file.

So the question is, Should I be using sleep, and if so how do I decide how long to sleep for? Should I be using an alternative?

Aucun commentaire:

Enregistrer un commentaire