Search code examples
rustpathfilepath

How to add a folder to a path before the filename?


How do I change "C:\foo\bar.txt" to "C:\foo\baz\bar.txt" using either Path or PathBuf?

I want to add a folder to the path immediately before the filename.


Solution

  • The Path type supports a number of methods to manipulate and destructure paths, so it should be straightforward to append a directory. For example:

    fn append_dir(p: &Path, d: &str) -> PathBuf {
        let dirs = p.parent().unwrap();
        dirs.join(d).join(p.file_name().unwrap())
    }
    

    I'm testing it on Linux, so for me the test looks like this, but on Windows you should be able to use C:\... just fine:

    fn main() {
        let p = Path::new(r"/foo/bar.txt");
        assert_eq!(append_dir(&p, "baz"), Path::new(r"/foo/baz/bar.txt"));
    }