无法连接到SQL数据库

时间:2015-06-04 10:51:18

标签: c# sql

我已将数据库文件(.mdf)附加到我的应用程序。该文件位于bin \ debug \ database文件夹中。但是当我创建安装文件并在其他计算机上安装我的应用程序时,我在连接数据库时遇到一些错误,例如:"尝试执行未经授权的操作","访问被拒绝"或" Database_log.mdf已存在" ... 我的app.config:

<?xml version="1.0"?>
<configuration>
    <configSections>
    </configSections>
     <connectionStrings>
        <add name="XtopazConnectionString"
        connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\Database\XTOPAZ.mdf;Initial Catalog=XTOPAZ;Integrated Security=True"
        providerName="System.Data.SqlClient" />
        </connectionStrings>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
        </startup>
</configuration>

我的连接字符串和连接功能:

 public static void openConnect()
    {
        try
        {
            if (File.Exists(Application.StartupPath + @"\Database\XTOPAZ.mdf"))
            {
                if (File.Exists(Application.StartupPath + @"\Database\XTOPAZ_log.ldf")) //delete current ldf file if it existed
                {
                    File.Delete(Application.StartupPath + @"\Database\XTOPAZ_log.ldf");
                }
                string s = ConfigurationManager.ConnectionStrings["XtopazConnectionString"].ConnectionString;

                //Set full permisstion access for database file
                DirectoryInfo dInfo = new DirectoryInfo(Application.StartupPath + @"\Database\XTOPAZ.mdf");
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
                dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                dInfo.SetAccessControl(dSecurity);
                dInfo.SetAccessControl(dSecurity);

                con.ConnectionString = s;
                con.Open();
            }
            else
            {
                Exception ex;
                ex = new Exception("Database file not found");
                throw ex;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error occured when trying to connect to database\r\nDetail: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

那么如何创建我的安装文件并在其他计算机上安装应用程序而没有任何错误?

1 个答案:

答案 0 :(得分:0)

您是否尝试过以管理员模式运行应用程序? 将清单文件添加到项目项目 - &gt;添加新项目 - &gt;应用程序清单文件。然后修改requestedExecutionLevel以匹配此行:

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />