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.
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 thefs::symlink_metadata
function and not thefs::metadata
function. Thefs::metadata
function follows symbolic links, sois_symlink
would always returnfalse
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(())
}