windowsrustsymlinkrust-2018

Check if a file is a symlink in Rust 2018 on Windows


I'm writing a small utility for myself that needs to be able to check if a file is a symlink or not.

Using FileType::is_symlink on Windows always returns false (goes for both symlinks to directories, and regular files).

Using regular Rust 2018 edition, is there any way to check if a file is a symlink on Windows?

In my searching, I came across: FileTypeExt - however this requires that you use unstable Rust, as far as I can tell.


Solution

  • Using File::metadata() or fs::metadata() to get the file type will always return false for FileType::is_symlink() because the link has already been followed at that point. The docs note that:

    The underlying Metadata struct needs to be retrieved with the fs::symlink_metadata function and not the fs::metadata function. The fs::metadata function follows symbolic links, so is_symlink would always return false for the target file.

    use std::fs;
    
    fn main() -> std::io::Result<()> {
        let metadata = fs::symlink_metadata("foo.txt")?;
        let file_type = metadata.file_type();
    
        let _ = file_type.is_symlink();
        Ok(())
    }