首页 > 解决方案 > c# adobe acrobat SDK:SDK退出后文件仍被锁定

问题描述

我正在使用 C# 和 adobe acrobat SDK。当程序由于 pdf 已经被压缩而引发错误时,我想移动 pdf。

但是,C# 抱怨该文件正在被另一个进程使用,我知道它与 SDK 而不是另一个程序有关。经过一些调试,我发现这compressPDFOperation.Execute是罪魁祸首。

如何关闭它以便移动文件?

 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);                   
            }
        }

标签: c#acrobat-sdk

解决方案


我找到了解决方案,这不是最佳做法,但我不知道其他方法。result.SaveAs(...)我已经在 try catch 语句之前以及在我将这些变量设置为 null 并运行垃圾回收之后声明了所有用于执行压缩的变量(sourceFileRef、compressPdfOperation、...) 。

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

推荐阅读