Writing a C# SDK program that opens and closes a Calc document leaving any open document open

I’m working on some programs that read and potentially modify Calc documents. So far I can do all of that successfully, but the code I use to end my program will also close any running instance of LibreOffice, although it offers to save the other open document if it has been changed.

What I want is to be able to save and close my document but only terminate LibreOffice if my program started it. My program opens the document I am working on in Hidden mode. In other words I want to be able to run my program without affecting anything else that is running.

To complicate things a bit, the document that is already open might be the same one my program is reading or modifying. Ideally I’d like to have this just work, with changes made to either copy of the document preserved. However I realize that that may be difficult or impossible, due to changes to a document being tentative until it is saved. Maybe if the already-open document has changes the user could be prompted to save it before my copy is opened?

Here is the code I have:

    XComponentContext XCC = uno.util.Bootstrap.bootstrap();
    XMultiServiceFactory XMSF = (XMultiServiceFactory)XCC.getServiceManager();
    XComponentLoader XCL =

    PropertyValue[] PV = new PropertyValue[2];
    PV[0] = new PropertyValue();
    PV[0].Name = "Hidden";
    PV[0].Value = new uno.Any(true);
    PV[1] = new PropertyValue();
    PV[1].Name = "ReadOnly";
    if (lreadonly) PV[1].Value = new uno.Any(true);
    else PV[1].Value = new uno.Any(false);
    XComponent XCo = XCL.loadComponentFromURL(pqfile,"_blank",0,PV);

    XSpreadsheets XSSs = ((XSpreadsheetDocument)XCo).getSheets();
    XNameAccess XNA = (XNameAccess)XSSs;
    XSpreadsheet XSS = (XSpreadsheet)XNA.getByName("Box Inventory").Value;
    .   [read and write cells]
    XModifiable XM = (XModifiable)XCo;
    XCloseable XCl = (XCloseable)XCo;

    XDesktop XD = (XDesktop)XCL;
    if (XD != null) XD.terminate();

I only partially understand this code, but it seems to work; I’ve copied it from various samples and documents.

Any ideas on how I could do what I want, or at least close to it?

Many thanks!