Search code examples
c#visual-studio-2010sql-server-ce

Access to database file not allowed (SQL Server Compact) in Visual Studio 2010 C#


First point: I believe this question has already been answered here but it doesn't solve my problem. I'm also not (yet) allowed to comment on the question because of my reputation is less than 50 points.

When my program is installed on a computer that doesn't have admin privileges, it throws this error

Access to database "PayeeList.SDF" is not allowed

when in App Manifest, I add start program as administrator, this problem doesn't come up, but it is a bit annoying when I start my program and it asks for admin permission, I want my program to run without admin permission.

these are my file installation properties and file properties of my database below.

File Installation Properties of visual studio setup deployment.

Properties

Second point:

Please let me know if I'm doing this correctly.

Solution in the original question on Stackoverflow:

Make sure you use |DataDirectory| in your connection string. Here is an example

connectionString="Data Source=|DataDirectory|MyDB.sdf"

If I change this will this fix my issue?

enter image description here

It gives me this ERROR when I click OK.

Third point: I still get this error when I click OK.

Require any more information, please let me know.


Solution

  • There might be two things to consider :

    1. Installation directory : Without Admin privilege, Windows will not allow to change any file in installation directory ( Program Files or Program Files (x86)).

      You can create your own directory and store your database in :

      User's Directory\AppData\Roaming\

      Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

      it is accessible to current logged-in user.

      For all users you can use :

      C:\ProgramData

      Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

      it is accessible to all users.

    2. ConnectionString : You can store connection string in Global Static Property Or variable so that it can be easily accessible within current application. You can use Application.StartupPath to get the current application directory.

    Or you can modify you connectionstring in App.config file :

    Connection String

    You can also use code to set dataDirectory path :

     string path =Application.StartupPath; // or Any Path
     AppDomain.CurrentDomain.SetData("DataDirectory", path);