Main menu:

Search

 
web
kriegermartin.de

Categories

May 2009
M T W T F S S
« Sep   Jun »
 123
45678910
11121314151617
18192021222324
25262728293031

Archives

AttachDbFilename

Today I tried to start a sample program which contains a connection string like this:

const string connectionString = @”Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\SampleInstanceStore.mdf; Integrated Security=True;Asynchronous Processing=True”;

I got the following error message:

System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users\Martin\Some more subfolders\SampleInstanceStore.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

The reason for the message is, that the SQL Server uses its own user account to access the database file. In the current case this was NetworkService - which had no access rights to the files. But it was not enough to grant NetworkService rights on the files or their folder. If AttachDbFilename is used without an additional parameter for the database name, then the database name is the path name of the database file. To get this name the SQL Server inspects -using its own account- all parent folders, up to root. So it needs at least read rights there.

Possible solutions:

  • User Instances: With user instance=true in the connection string another instance of SQL Server Express (and only Express!) will be started. This instance uses the credentials of the user. Unfortunately Microsoft intends to remove this feature in future versions.
  • Server Manager: Use the server manager to create or attach the database and change the connection string appropriate.
  • Local System: In theory it would be possible to run SQL Server using a less restricted account, like LocalSystem. Of course nobody will ever want to do this, as it’s a huge security leak.
  • Initial Catalog: If a database/initial catalog parameter is used, in addition to the AttachDbFilename parameter, then this name is used for the database. So it is sufficient to give the the .mdf file and its containing folder appropriate access rights.