Search This Blog

Saturday 2 November 2024

Search Zip and Nested Zip Folder and Extract Zip File and Upload

public void TestExtractZipFileAndUpload()
{
    string path = "E:\\Test.zip";
    byte[] bytes = File.ReadAllBytes(path);

    ExtractZipFileAndUpload(bytes);
}

protected void ExtractZipFileAndUpload(byte[] bytes)
{
    string fullPath = string.Empty;
    string extractFullPath = string.Empty;

    try
    {
        string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        string zipFolderContainer = Path.Combine(baseDirectory, "Zip Folder Container");

        if (!Directory.Exists(zipFolderContainer))
            Directory.CreateDirectory(zipFolderContainer);

        string zipName = new Random().Next(1000, 9999).ToString();
        fullPath = Path.Combine(zipFolderContainer, $"{zipName}.zip");

        File.WriteAllBytes(fullPath, bytes);

        string extractedFolderContainer = Path.Combine(baseDirectory, "Extracted Zip Folder Container");
        string extractPathFolder = new Random().Next(1000, 9999).ToString();
        extractFullPath = Path.Combine(extractedFolderContainer, extractPathFolder);

        if (!Directory.Exists(extractFullPath))
            Directory.CreateDirectory(extractFullPath);

        System.IO.Compression.ZipFile.ExtractToDirectory(fullPath, extractFullPath);

        string[] extractedFiles = Directory.GetFiles(extractFullPath, "*.*", SearchOption.AllDirectories);

        foreach (string extractedFile in extractedFiles)
        {
            try
            {
                string fileExtension = Path.GetExtension(extractedFile);

                if (fileExtension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    byte[] nestedZipBytes = File.ReadAllBytes(extractedFile);
                    ExtractZipFileAndUpload(nestedZipBytes); // Recursive call
                }
                else
                {
                    byte[] fileBytes = File.ReadAllBytes(extractedFile);
                    string fileName = Path.GetFileName(extractedFile);

                    //Upload Code
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    finally
    {
        if (File.Exists(fullPath))
            File.Delete(fullPath);

        if (Directory.Exists(extractFullPath))
            Directory.Delete(extractFullPath, true);
    }
}

No comments:

Post a Comment