0 votes
by (350 points)

I want to use Rebex.IO.ActionOnExistingFiles.Rename to rename duplicates but also need to set a custom 'CreationTime' of the file and without knowing its new name there appears to be no way of doing this?

I assume I would be best just checking the file exists before adding and doing this myself?

    using (var zip = new ZipArchive(zipFilename))
    {
        string archiveFilePath = "rename.txt";
        zip.AddFile(new MemoryStream(Encoding.UTF8.GetBytes("old file")), archiveFilePath, Rebex.IO.ActionOnExistingFiles.Rename);
        zip[archiveFilePath].CreationTime = DateTime.Now.AddMonths(-6);

        zip.AddFile(new MemoryStream(Encoding.UTF8.GetBytes("new file")), archiveFilePath, Rebex.IO.ActionOnExistingFiles.Rename);
        zip[archiveFilePath].CreationTime = DateTime.Now;
    }
Applies to: Rebex ZIP

1 Answer

0 votes
ago by (75.4k points)

Unfortunately, it is not possible to set item properties during compression. However, you can utilize the ProgressChanged event to get information about successfully processed files and update items using that after the compression is complete. For example like this:

var processedFiles = new List<string>();
zip.ProgressChanged += (s, e) =>
{
    if (e.OperationStep == ArchiveOperationStep.FileProcessed)
        processedFiles.Add(e.ArchiveItemPath);
};

zip.Add("c:/data", "/", 0, 0, ActionOnExistingFiles.Rename);

foreach (var file in processedFiles)
{
    var item = zip[file];
    var now = DateTime.Now;
    item.CreationTime = now;
    item.LastWriteTime = now;
    item.LastAccessTime = now;
}

If you want to set properties of renamed files only, you can utilize the ProblemDetected event to capture paths of renamed files and use it in ProgressChanged handler:

var renamedFiles = new HashSet<string>();
zip.ProblemDetected += (s, e) =>
{
    if (e.ProblemType == ArchiveProblemType.FileExists)
    {
        // store external path, which will remain unmodified during the process
        renamedFiles.Add(e.ExternalItemPath);
        e.Action = ArchiveProblemActions.Rename;
    }
};

var processedFiles = new List<string>();
zip.ProgressChanged += (s, e) =>
{
    if (e.OperationStep == ArchiveOperationStep.FileProcessed)
    {
        // store only successfully renamed files
        if (renamedFiles.Contains(e.ExternalItemPath))
            processedFiles.Add(e.ArchiveItemPath);
    }
};
...