使用 Poco::zip 添加新目录始终给出异常

Add new Directory with Poco::zip always give Exception

本文关键字:异常 新目录 Poco zip 添加 使用      更新时间:2023-10-16

我正在构建一个压缩/解压缩函数,目前,我只能将 1 个单个文件压缩成一个 zip 文件。每次我添加新目录或递归添加目录时,它总是给我异常。

这是我的ZipFile函数:

Poco::DateTime(Timestamp);
set <string> extensionsSet;
std::ofstream fos(target, ios::binary);
Poco::Zip::Compress c(fos, true);
for (int i = 0; i < extensions.Size(); i++) {
string ext = std::dynamic_pointer_cast<String>(extensions.operator[](i))->GetPrimitive();
extensionsSet.insert(ext);
}
c.setStoreExtensions(extensionsSet);//set extensions List 

Poco::File aFile(source);
if (aFile.exists())
{
Poco::Path p(aFile.path());
if (aFile.isDirectory())
{
Poco::Path sourceDir(source);
Poco::Path targetDir(target);
c.addDirectory(targetDir, Poco::DateTime(Timestamp));// give exception
targetDir.makeDirectory();
c.addRecursive(sourceDir);
}
else if (aFile.isFile())
{
c.addFile(p, p.getFileName());
}
}
else {
_log.EndMethod();
throw new FileNotFoundException("File Not Found");
}

c.close(); // MUST be done to finalize the Zip file
fos.close();

这是我的例外,下面的代码块在 Poco 的 addDirectory 方法中:

if (!ZipCommon::isValidPath(fileStr))
throw ZipException("Illegal entry name " + fileStr + " containing parent directory reference");

在"Poco::P ath"中有一个成员叫做"absolute"。 您可以通过构造函数将绝对设置为 false

否则会抛出 ZipException,因为此函数返回"false":

bool ZipCommon::isValidPath(const std::string& path)
{
try
{
if (Path(path, Path::PATH_UNIX).isAbsolute() || Path(path, Path::PATH_WINDOWS).isAbsolute())
return false;
}
...
}

下面是一个示例:

std::ofstream fos(target, ios::binary);
Poco::Zip::Compress compress(fos, true);
std::vector<std::string> dirs; // parent dirs in zip file
Poco::Path myPath(false); // set path to non-absolute
// add parent directories
for (auto& dir : dirs)
{
myPath.pushDirectory(dir);
}
//add file
myPath.setFileName("FileName.txt");
//add file to archive
compress.addFile(theFile, relativePath);
//close archive and get zipArchiveObject
ZipArchive zipArchive(compress.close());