简体   繁体   中英

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.

Visual Studio安装程序部署的文件安装属性。

性质

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?

在此处输入图片说明

当我单击确定时,它给我这个错误。

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

Require any more information, please let me know.

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 :

连接字符串

You can also use code to set dataDirectory path :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM