Egor Kadochnikov
Egor Kadochnikov

Reputation: 41

How to change the name of a new .zip file automatically?

I want to implement a function, that will take files from one directory, compress them in .zip and put that archive in another one directory. The problem is that if i call this function more than once, i have to define the name of a new .zip file in code manually, so that it must be always unique. Otherwise i get an exception "System.IO.IOException: 'The destination file already exists.' How could i make it so, that a name for every new .zip will be generate automatically?(e.g. new_zip_1, new_zip_2, etc.)

I use a function that allows to make .zip file in choosen directory:

ZipFile.CreateFromDirectory(startPath, zipPath);

class ZipController
{
    public void Zip()
    {
        string startPath = @"D:\Start\ToZip";
        string zipPath = @"D:\NewZip";

        ZipFile.CreateFromDirectory(startPath, zipPath);
    }
}

Upvotes: 3

Views: 594

Answers (1)

soulflyman
soulflyman

Reputation: 520

If it dos not have to be a incrementing number in the name of the ZIP so I would use date and time. It is less code and it is much more unlike to get the same filename twice.

To get date and time in a filename friendly format:

DateTime.Now.ToString("yyyy-mm-dd_hh-mm-ss")

So your code could look like this:

class ZipController
{
    public void Zip()
    {
        string startPath = @"D:\Start\ToZip";
        string dateTime = DateTime.Now.ToString("yyyy-mm-dd_hh-mm-ss");
        string zipPath = @"D:\NewZip\new_zip_" + dateTime + ".zip";

        ZipFile.CreateFromDirectory(startPath, zipPath);
    }
}

Upvotes: 2

Related Questions