Pankaj Saha
Pankaj Saha

Reputation: 959

Create zip folder in amazon S3

I have to created a folder in the amazon S3. Now have to convert that folder in the zip file. I have used the DotNetZip Liberary to convert to the .zip file. Here is the link for that

http://dotnetzip.codeplex.com/wikipage?title=CS-Examples

public void ConvertToZip(string directoryToZip, string zipFileName)
{
    try
    {

        using (client = DisposableAmazonClient())
        {
            var sourDir = new S3DirectoryInfo(client, bucket, directoryToZip);

            var destDir = new S3DirectoryInfo(client, bucket, CCUrlHelper.BackupRootFolderPhysicalPath);

            using (var zip = new ZipFile())
            {
                zip.AddDirectory(sourDir.FullName); // recurses subdirectories
                zip.Save(Path.Combine(destDir.FullName, zipFileName));
            }
        }

        logger.Fatal("Successfully converted to Zip.");
    }
    catch (Exception ex)
    {
        logger.Error("Error while converting to zip. Error : " + ex.Message);
    }
}

When I run the code it is showing the error "The given path's format is not supported."

Upvotes: 2

Views: 3451

Answers (1)

Norm Johanson
Norm Johanson

Reputation: 3177

The S3DirectoryInfo emulates a directory structure but it is not an actual directory structure and DotNetZip has no knowledge of how to handle a string pointing to an object in S3. In order for you to do this you are going to have to download the files, zip them up, and then upload the resulting zip file. Here is some sample code that shows how you could do that.

class Program
{
    static void Main(string[] args)
    {
        var zipFilename = @"c:\temp\data.zip";
        var client = new AmazonS3Client();
        S3DirectoryInfo rootDir = new S3DirectoryInfo(client, "norm-ziptest");
        using (var zip = new ZipFile())
        {
            zip.Name = zipFilename;
            addFiles(zip, rootDir, "");
        }

    // Move local zip file to S3
    var fileInfo = rootDir.GetFile("data.zip");
    fileInfo.MoveFromLocal(zipFilename);
}

static void addFiles(ZipFile zip, S3DirectoryInfo dirInfo, string archiveDirectory)
{

    foreach (var childDirs in dirInfo.GetDirectories())
    {
        var entry = zip.AddDirectoryByName(childDirs.Name);
        addFiles(zip, childDirs, archiveDirectory + entry.FileName);
    }

    foreach (var file in dirInfo.GetFiles())
    {
        using (var stream = file.OpenRead())
        {                    
            zip.AddEntry(archiveDirectory + file.Name, stream);

            // Save after adding the file because to force the 
            // immediate read from the S3 Stream since 
            // we don't want to keep that stream open.
            zip.Save(); 
        }
    }
}

}

Upvotes: 3

Related Questions