"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?

How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?

Posted on 2025-02-26
Browse:299

How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?

Zipping Content Inside a Folder Without Including the Root Folder

Problem: Zipping files within a folder results in an extracted structure that includes the root folder, whereas the desired outcome is to extract the files without the root folder.

Code Attempt:

The following code is an attempt to zip the directory structure:

func Zipit(source, target string) error {
    zipfile, err := os.Create(target)
    ...
    header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
    ...
}

Troubleshooting:

In the provided code, the issue lies in the line where the baseDir is being added to the header.Name. To exclude the root folder from the extracted structure, remove the baseDir from the filename.

Solution:

Replace the following line:

header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))

with:

header.Name = strings.TrimPrefix(path, source)

Alternative Approaches:

Instead of manually modifying the header name, you could also use the following alternative approach to exclude the root folder during extraction:

walker := filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
    // Ignore the root directory
    if info.IsDir() && path == source {
        return filepath.SkipDir
    }
    ...
})
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3