sql-serversql-server-2012file-listing

XP_DirTree in SQL Server


Variations to this have been asked. I have no problem searching a local directory with the below piece of code.

EXEC MASTER.sys.xp_dirtree 'C:\', 1, 1

When I switch the path to a network location the results are empty.

EXEC MASTER.sys.xp_dirtree '\\Server\Folder', 1, 1

I first thought maybe it was something to do with permissions. I added the SQL Server Service to the ACL list on the shared volume as well as the security group.

Any help or direction to point me in is greatly appreciated or even another way to get a list of files in a directory and sub directories.

[Edited]


Solution

  • The two things to look out for are:

    Just to have it stated, another option is to do away with xp_dirtree altogether and instead use SQLCLR. There is probably sample C# code on various blogs. There are also a few CodePlex projects that have file system functions and might also provide a pre-compiled assembly for those that don't want to deal with compiling. And, there is also the SQL# library that has several filesystem functions including File_GetDirectoryListing which is a TVF (meaning: you can use it in a SELECT statement with a WHERE condition rather than needing to dump all columns and all rows into a temp table first). It is also fully-streamed which means it is very fast, even for 100k or more files. Please note that the FILE_* functions are only in the Full version (i.e. not free) and I am the creator of SQL#, but it does handle this situation quite nicely.