Convert std::path::Path to path string suitable for a ZIP file

⚓ Rust    📅 2025-07-29    👤 surdeus    👁️ 12      

surdeus

Warning

This post was published 127 days ago. The information described in this article may have changed.

In my JAR file tool, I just encountered an issue on a Windows system.
When I build the tool for Linux it worked fine, but on Windows it did not display or update the files within the ZIP files.
It turned out, that the ZIP file library requires paths to the files within the archive to be POSIX style, i.e. with a / instead of a \. Because my program used native conversion of the paths to string, it obviously failed on windows.

I wrote a helper function to serialize the paths in an OS-independent manner:


/// Converts a `Path` to a string representation suitable for use in a ZIP file.
fn path_to_zip_file_path(path: &Path) -> Option<String> {
    let mut components = Vec::new();

    for component in path.components() {
        components.push(component.as_os_str().to_str()?);
    }

    Some(components.join("/"))
}

I did not find such a functionality within the std::path library or the zip crate.
Do you know of any standard library features that do this, which I may have overlooked?

2 posts - 1 participant

Read full topic

🏷️ Rust_feed