Question

I'm creating a maintenance tool and I need to let the user to select a file location for new databases. I would use the FolderBrowserDialog except that I want to show the user the directory structure from the point of view of the machine that SQL Server is actually on rather than the client the tool is being run from.

I know SSMS does this whenever you are selecting backup locations, so I'm wondering if the dialog it uses is available or if there's a way to make the FolderBrowserDialog behave in this manner. It seems that when you do it through SMSS you get to bypass certain permissions issues (i.e. the server doesn't need to be shared or anything).

Suggestions?

Was it helpful?

Solution

I've been working on a similar task, and came across the same problem. I would happily share the ready solution, but I signed a deal with the devil, and the company owns everything I make while working for them. But the gist of it is this:

  1. Use the Server.EnumAvailableMedia method to get the hard drives on the server.
  2. Call the xp_dirtree stored procedure to get the files and sub-directories in the given path

I ended up making my own file dialog Form using a TreeView. The code that populates it should look something like:

public partial class RemoteFileDialog : Form
{
    public Server server = new Server( new ServerConnection("ServerName", "User", "Password") );

    /* ... */

    public void getServerDrives()
    {
        DataTable d = server.EnumAvailableMedia();
        foreach (DataRow r in d.Rows)
            treeView.Nodes.Add( new TreeNode(r["Name"].ToString() );
    }

    /* ... */

    //populate a node with files and subdirectories when it's expanded
    private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
    {
        DataSet ds = server.ConnectionContext.ExecuteWithResults(string.Format("exec xp_dirtree '{0}', 1, 1", e.Node.FullPath));
        ds.Tables[0].DefaultView.Sort = "file ASC"; // list directories first, then files
        DataTable d = ds.Tables[0].DefaultView.ToTable();
        foreach (DataRow r in d.Rows)
            e.Node.Nodes.Add( new TreeNode(r["subdirectory"].ToString());
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top