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.
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+.
**
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With