views:

650

answers:

3

Is there a way to tell using C# if a file is real or a symbolic link?

I've dug through the MSDN W32 docs (http://msdn.microsoft.com/en-us/library/aa364232(VS.85).aspx), and can't find anything for checking this. I'm using CreateSymbolicLink from here, and it's working fine.

+1  A: 

GetFileInformationByHandle fills a BY_HANDLE_FILE_INFORMATION structure which has a field dwFileAttributes where bits are set with info about the file's attributes (details here). In particular, look at the bit at mask...:

FILE_ATTRIBUTE_REPARSE_POINT 1024 0x0400

A file or directory that has an associated reparse point, or a file that is a symbolic link.

Alex Martelli
I've tried using the System.IO.File.GetAttributes() method, which I believe implements this, but it only seems to work on Junction Points, and not Symbolic Links.
mattdwen
Can you try the syscall itself? I have no Vista install at hand to try this myself.
Alex Martelli
Same thing - getting 32, which is Archive only.I've just found out I may have to abort this method and use Hard Links anyway, but it would be good to figure it.
mattdwen
Ah well - looks like MSDN is incorrect on this point, then:-(.
Alex Martelli
And I'm getting the same thing for Hard Links as well. Never shows it as a reparse point.
mattdwen
Hrmm just found FSCTL_SET_REPARSE_POINT (http://msdn.microsoft.com/en-us/library/aa364595(VS.85).aspx). Maybe if it's created that way it will return 1024.Can't be bothered though - the date stamps and file sizes will be different in my scenario if it's not a link, so that will suffice.
mattdwen
A: 

According to this answer, getting the System.IO.FileAttributes for the file (via File.GetAttributes), and testing for the ReparsePoint bit, works. If the bit is set, it is a symlink. If not, it is a regular file (or hardlink).

Cheeso
A: 

In addition to the above-described methods you can also use Windows API Code Pack. Read about ShellObject and isLink property.

shidzo