问题描述
考虑以下 C# 代码:
class AAA
{
private:
int m_val;
public:
AAA(int a) : m_val(a) {}
};
class BBB
{
private:
AAA a;
public:
BBB(const AAA& a_) : a(a_) {}
};
int main()
{
AAA a(5),a1(10);
BBB b(a),b1(a1);
b = b1;
BBB b2( AAA(5) );
b = b2;
}
如果 try
{
using (new PdfReader(filename))
{
}
}
catch
{
}
finally
{
File.Delete(filename);
}
指向一个非 pdf 文件,filename
构造函数抛出异常(如预期),但也不会释放它内部创建的 PdfReader
,尽管被调用FileStream
块。因此,尝试删除 using
块中的文件会引发异常 finally
实际上,如果构造函数抛出异常,应该不会导致锁定任何资源。因此,即使在没有 The process cannot access the file '<filename>' because it is being used by another process.
块的情况下调用 PdfReader
构造函数时,上面的代码也应该删除非 pdf 文件。
明显的解决方法是像这样实例化 using
:
PdfReader
它确实有效,但不期望使用 using (var fileStream = new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read))
using (new PdfReader(fileStream))
{
}
参数的 PdfReader
构造函数重载的当前行为。
解决方法
这确实是 iText 的一个错误,但它是已知问题,并且已经在最新的开发版本中修复。 iText 7.1.16 版本将包含此修复程序,但如果您现在需要此修复程序,您可以使用 artifactory https://repo.itextsupport.com/webapp/#/artifacts/browse/tree/General/snapshot
中的 SNAPSHOT 版本