在亚马逊S3中创建zip文件夹

时间:2013-03-11 12:00:56

标签: c# amazon-s3 dotnetzip

我必须在亚马逊S3中创建一个文件夹。现在必须在zip文件中转换该文件夹。我使用DotNetZip Liberary转换为.zip文件。这是

的链接

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);
    }
}

当我运行代码时,它显示错误“不支持给定路径的格式。”

1 个答案:

答案 0 :(得分:3)

S3DirectoryInfo模拟目录结构,但它不是实际的目录结构,并且DotNetZip不知道如何处理指向S3中的对象的字符串。为了让您这样做,您将不得不下载文件,压缩它们,然后上传生成的zip文件。以下是一些示例代码,说明了如何做到这一点。

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(); 
        }
    }
}

}