我有一个在Visual Studio中运行的C#.NET程序。它的功能是根据文件名合并PDF文件。 它适用于前12个左右的PDF,但在某个时刻突然以代码0退出。我没有使用多线程,我使用的PDF库是iTextSharp。
public static string MergePDFs(List<string> fileNames, ref string targetPdf)
{
string merged = "";
using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
PdfReader reader = null;
try
{
document.Open();
foreach (var file in fileNames)
{
reader = new PdfReader(file);
pdf.AddDocument(reader);
reader.Close();
}
}
catch (Exception)
{
// merged = "false";
if (reader != null) reader.Close();
}
finally
{
if (document != null)
{
Console.WriteLine("Closing document.");
document.Close(); // exits here
Console.WriteLine("Document closed.");
}
}
}
return merged;
}
调试器中的输出是:
...
Closing document.
The program has exited with code 0 (0x0)
答案 0 :(得分:0)
通过catch块打印出异常,但从未到达过。 try块执行成功。删除try / catch / finally块“修复”了问题。
这只是部分修复,因为现在不再有办法处理错误。
public static string MergePDFs(List<string> fileNames, ref string targetPdf)
{
string merged = "";
using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
PdfReader reader = null;
document.Open();
foreach (var file in fileNames)
{
reader = new PdfReader(file);
pdf.AddDocument(reader);
reader.Close();
}
document.Close();
}
return merged;
}