Inlcude an already opened document into a LINQ template throws error

Hi there
I try to include a document into a LINQ template (as described here) using the following syntax:

<<doc [VerzeichnisRM +"DocumentToBeIncluded.docx"] -build>>

This works fine when the document to be included is not already opened in Word. If the document to be included is already opened in MS Word, I get the following error calling the engine.BuildReport() method:

Cannot load a document using the provided string value: 'E:\dev\ZRPMicroServices\MicroServices\DocumentGeneratorService\DocumentGeneratorService.Tests\Generator\Sources\RM\DocumentToBeIncluded.docx'. A string expression providing document data should return a file path, an URI, or Base64-encoded document bytes.

How can I include documents into a LINQ template that may be already opened by MS Word or by another instance of Aspose Words?

Many Thanks,
Dani

@tibitabi I am afraid there is no way to insert document, which is currently opened by MS Word, because MS Word locks the file. There are no problems with inserting document which is opened by another instance of Aspose.Words, because Aspose.Words fully loads the document into the memory and does not lock the file.

@alexey.noskov Thanks a lot for your answer.
How would you rate the following solution: We write a utility method which loads the already opened document using a FileStream with FileShare.ReadWrite.

So, instead of:
<<doc [VerzeichnisRM+"DocumentToBeIncluded.docx"] -build>>

We use:
<<doc [Util.Include(VerzeichnisRM+ "DocumentToBeIncluded.docx")] -build>>

Whereby Util.include looks as follows:

public static Document Include(string includePath)
{
    var doc = new Document();

    try
    {
        using var docStream = new System.IO.FileStream(includePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        doc = new Document(docStream);
    }
    catch
    {
        //ignored
    }

    return doc;
}

Do you see any problem in that approach? How do you rate it performance wise?

Many thanks,
Dani

@tibitabi There are no problems with this code, since internally Aspose.Words also loads the document is to be included into Document object. So passing Document object into <<doc ...>> is fine.

OK, many thanks.
Cheers,
Dani

1 Like