tags:

views:

36

answers:

2

Hi

I open a document with

WordApplication1.Connect;
WordApplication1.Documents.OpenOld(FileNameOLE,EmptyParam,EmptyParam,EmptyParam,
    EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam);
WordApplication1.Visible:=true;

and I want to save it to a stream after it is closed but I get cannot open file used by another process error. What to do ? thanks for help.

sample

procedure TPatient.WordApplication1Quit(Sender: TObject);
  var mem:TMemoryStream;
begin
  WordApplication1.Disconnect;
  WordApplication1.Quit;
  //I get filename to global widestring variable File_OLE
  mem:=Tmemorystream.Create;
  mem.LoadFromFile(File_OLE); -------->>>>error here
  mem.Position:=0;
A: 

It seems like Word is still blocking the access to the file. So you may have to wait a few milliseconds to seconds until the file is released. You can achieve this by Sleep and/or retrying to save a few times

Scoregraphic
Using sleep, the quit event doesn't end and greater chance the file is still opened when your application wake up again. For a simple solution, use a timer instead.
jachguate
A: 

In your sample procedure, Word is still running when you want to load the document in your TMemoryStream. Word is handling it's quit event at that time (go figure :P ) and hasn't shutdown yet.

What you could do is start a timer (TTimer with an interval of 500/1000) on the quit event and open your document in the timer event. Also don't call WordApplication1.Quit, because you are already quitting, just disconnect your WordApplication1.

An even better solution is to not rely on the quit event. Because when you start Word as in your first code section, and you open another Word document from Windows Explorer, the quit event won't come by when you close the document your application opened. Word will still remain active because it's hosting the other document too.

Add a TWordDocument to your form and when you open the document, connect the TWordDocument to the opened document. In the TWordDocument.Close event you can start a Timer and when the Timer fires, you can load your Document. An even better way is to not use timers but just save the document on the OnClose event to another file (.SaveAs) and load that file into the memorystream. This way you can be sure that the file is not opened by Word.

The_Fox