Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Database - How can I find out the Default Data Directory?

I want to be able to create a database within my C# WinForm application using the code I found HERE.

But I need to find a way to get the default data directory for that particular SQL Server Instance. I am wondering if there was a easy way to accomplish this that is able to be used on the various versions of SQL Server.

Thanks in advance.


EDIT

I found the following Select that will return the default data directory on the remote server:

SELECT 
    SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1)
FROM master.sys.master_files 
WHERE database_id = 1 
    AND file_id = 1

This solution will only work on SQL Server 2005+.

**

like image 319
Mark Kram Avatar asked Nov 25 '22 19:11

Mark Kram


1 Answers

Here is a better solution suggested by Alex Aza.
The solution is:

using (var connection = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
{
    var serverConnection = new ServerConnection(connection);
    var server = new Server(serverConnection);
    var defaultDataPath = string.IsNullOrEmpty(server.Settings.DefaultFile) ? server.MasterDBPath : server.Settings.DefaultFile;
    var defaultLogPath = string.IsNullOrEmpty(server.Settings.DefaultLog) ? server.MasterDBLogPath : server.Settings.DefaultLog;
}

It requires Microsoft.SqlServer.Smo.dll and Microsoft.SqlServer.ConnectionInfo.dll to be referenced. One can find these dlls in folder C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies. They are distributed with SQL installation.

like image 193
dmigo Avatar answered Dec 11 '22 09:12

dmigo