Good afternoon, please tell me how can I add files with the same name to the archive? To be like copying, the file becomes file(1).* and there are two files file and file(1) . I am using Ionic.Zip
string BackupDir = @"C:\Users\Desktop\dir\backup.zip";
string PathToFolder = @"C:\Users\Desktop\dir";
string[] AllFiles = Directory.GetFiles(PathToFolder, "*.*", SearchOption.AllDirectories);
using (ZipFile zip = new ZipFile(BackupDir, Encoding.UTF8))
{
foreach (string file in AllFiles)
{
try
{
DateTime FileCreationTime = File.GetCreationTime(file);
if (FileCreationTime >= DateTime.Now - new TimeSpan(60, 0, 0, 0))
{
Console.WriteLine(file);
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
zip.AddFile(file, "");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
zip.Save(BackupDir);
}
}
CodePudding user response:
Try this:
//keep track of fileNames
var fileNames = new HashSet<string>(StringCompaer.OridialIgnoreCase);
foreach (string file in AllFiles)
{
try
{
DateTime FileCreationTime = File.GetCreationTime(file);
if (FileCreationTime >= DateTime.Now - new TimeSpan(60, 0, 0, 0))
{
Console.WriteLine(file);
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
var fileName = Path.GetFileName(file);
if (fileNames.Add(fileName))
zip.AddFile(file, ""); //fileName could be added to fileNames = it is unique
else
{
//start with 1
int counter = 1;
//loop till you found a fileName thats not occupied
while (true)
{
//build the new file name
var newFileName = $"{Path.GetFileNameWithoutExtension(fileName)} - {counter}{Path.GetExtension(fileName}";
if (fileNames.Add(newFileName))
{
fileName = newFileName; //use the new fileName
break; //break the loop
}
//increase counter if newFileName is already in the list fileNames
counter ;
}
var zipFileEntry = zip.AddFile(file, "");
zipFileEntry.FileName = fileName;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
zip.Save(BackupDir);
}
CodePudding user response:
Check if file exists and add suffix to it's name.
Something like:
int nameCount = 1;
fileName = file.Name;
while(fileName exists in archive)
{
nameCount ;
fileName = file.Name "_" nameCount;
}