Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql SMO: How to get path of database physical file name?

Tags:

sql-server

smo

I am trying to return the physical file path of a database's mdf/ldf files.

I have tried using the following code:

Server srv = new Server(connection);
Database database = new Database(srv, dbName);

string filePath = database.PrimaryFilePath;

However this throws an exception "'database.PrimaryFilePath' threw an exception of type 'Microsoft.SqlServer.Management.Smo.PropertyNotSetException' - even though the database I'm running this against exists, and its mdf file is located in c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL

What am I doing wrong?

like image 289
flayto Avatar asked Jan 23 '09 20:01

flayto


People also ask

How do I find the database path to a file in SQL Server?

You have two native options for finding out where the SQL server stores its database files: either right-click on the instance name in SQL Server Management Studio (SSMS) and navigate to the 'Database Settings' tab, or use a T-SQL query.

How do I find the physical path in SQL Server?

If you ever need to know where your database files are located, run the following T-SQL code: USE master; SELECT name 'Logical Name', physical_name 'File Location' FROM sys. master_files; This will return a list of all data files and log files for the SQL Server instance.

Where is my database MDF file?

The mdf and ldf can be set for each Microsoft SQL database, by right-clicking on the database, in Microsoft SQL Server Management Studio and selecting Properties. In the Database Properties Select Files. In this window, the current settings for the mdf and ldf are displayed.


1 Answers

Usually the problem is with the DefaultFile property being null. The default data file is where the data files are stored on the instance of SQL Server unless otherwise specified in the FileName property. If no other default location has been specified the property will return an empty string.

So, this property brings back nothing (empty string) if you didn't set the default location.

A workaround is to check the DefaultFile property, if it returns an empty string use SMO to get the master database then use the Database.PrimaryFilePath property to retrieve the Default Data File Location (since it hasn't changed)

Since you say the problem is with your PrimaryFilePath:

  • Confirm that your connection is open
  • Confirm that other properties are available
like image 69
Noah Avatar answered Oct 02 '22 03:10

Noah