我已将我的数据库文件(.mdf)放在bin \ debug文件夹中并使用此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);
}
}
我在Visual Studio 2012中使用InstallShield创建setup.exe并将其安装在其他计算机上(在我的C#项目中,没有错误),我看到这个错误:
我该如何解决这个问题?我用谷歌搜索了它,但我无法找到解决方案。
答案 0 :(得分:0)
此AttachDbFileName=
方法仅与SQL Server Express 一起使用 - 因此您必须确保本地SQL Server Express实例存在并正在运行。
它的默认实例名称为.\SQLEXPRESS
- 所以我建议您尝试使用此连接字符串:
<add name="XtopazConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database\XTOPAZ.mdf;Initial Catalog=XTOPAZ;Integrated Security=True"
providerName="System.Data.SqlClient" />