7

I am developing a web application. I need to get the database file path. What's the way to get the database file path in c#? for example:

E:/Program Files/Microsoft SQL Server/MSSQL.1/MSSQL/Data/MyDatabase.mdf
slugster
  • 49,403
  • 14
  • 95
  • 145
DEN
  • 1,893
  • 7
  • 27
  • 51
  • 3
    Why is this question tagged asp.net? This has more to do with SQL Server than ASP. – Merlyn Morgan-Graham Nov 16 '11 at 03:20
  • @Merlyn, My project is connected with the database and the ConnectionString is stated in webconfig. So im curious whether i can get the database path through the webconfig or not. :) – DEN Nov 16 '11 at 03:25
  • @DEN you can use the `connectionString` in your `web.config` to execute the query against your database. See my answer below. –  Nov 16 '11 at 03:29
  • @DEN: +1; In case it is important for your app, some databases don't have files - they are in-memory only. So the solution will only give you the right answer for SQL Server. It is in your tags, but I wanted to make sure you knew that there's no general answer applicable to all databases. – Merlyn Morgan-Graham Nov 16 '11 at 03:32

2 Answers2

16
select physical_name
from sys.database_files
where type = 0

The above is the SQL query to execute. Below is the C# code that will retrieve and store this data in a string:

SqlConnection DbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CStringName"].ConnectionString);
SqlCommand GetDataFile = new SqlCommand();
GetDataFile.Connection = DbConn;
GetDataFile.CommandText = "select physical_name from sys.database_files where type = 0";

try
{
    DbConn.Open();
    string YourDataFile = (string) GetDataFile.ExecuteScalar();
    DbConn.Close();
}
catch (Exception ex)
{
    DbConn.Dispose();
}
-2

Server.mappath will return the path

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
Ashok Padmanabhan
  • 2,110
  • 1
  • 19
  • 36
  • 2
    MapPath maps a virtual to physical path on the server. There is no virtual path to the mdf file. – Jason Nov 16 '11 at 03:21
  • That is assuming SQL Server is running on the same machine as the web site, which may or may not be the case. Also, Server.MapPath is is not really intended to be used for file paths that are outside of the virtual directory hierarchy (but may be possible), see here for more info: http://stackoverflow.com/questions/3422270/how-to-use-server-mappath-to-get-location-outside-website-folder-in-asp-net – Rich Nov 16 '11 at 03:27
  • It works for the mdf file in the app_Data folder which is what i was thinking of – Ashok Padmanabhan Nov 16 '11 at 04:11