Search code examples
c#acrobat-sdk

c# adobe acrobat SDK: file is still locked after SDK quit


I'm working with C# and adobe acrobat SDK. When the program throws an error due to the pdf already being compressed I want to move the pdf.

However, C# complains that the file is being used by another process and I know it has to do with the SDK and not another program. After some debugging I found out that compressPDFOperation.Execute is the culprit.

How can I close it so that I can move the file?

 try {

 // Initial setup, create credentials instance.
            Console.WriteLine(".json: " + Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json");
            Credentials credentials = Credentials.ServiceAccountCredentialsBuilder()
                            .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json")
                            .Build();

            // Create an ExecutionContext using credentials and create a new operation instance.
            ExecutionContext executionContext = ExecutionContext.Create(credentials);
            CompressPDFOperation compressPDFOperation = CompressPDFOperation.CreateNew();

            // Set operation input from a source file.
            FileRef sourceFileRef = FileRef.CreateFromLocalFile(directory + @"\" + pdfname);
            compressPDFOperation.SetInput(sourceFileRef);

            // Execute the operation.
            FileRef result = compressPDFOperation.Execute(executionContext);

            // Save the result to the specified location.
            //if pdf is part of a group, the group directory name will be stored in fileGroupDirectory
            string fileGroupDirectory = directory.Replace(sourceDir, "");
            
            result.SaveAs(finishedDir + fileGroupDirectory + pdfname);
} 
catch (ServiceApiException ex)
 {
            Console.WriteLine("Exception encountered while executing operation", ex.Message);

            if (ex.Message.Contains("The input file is already compressed"))
            {
               File.Move(file, finishedDir + fileGroupDirectory + fileName);                   
            }
        }

Solution

  • I've found a solution , it's not best practice but I don't know an other way to do it. I've declared all the variables used to execute the compression (sourceFileRef, compressPdfOperation, ...) before the try catch statement and after result.SaveAs(...) I set those variables to null and run the garbage collection.

            compressPDFOperation = null;
            result = null;
            sourceFileRef = null;
            executionContext = null;
            credentials = null;
            GC.Collect();