Search code examples
c#connection-stringapp-configsqlconnectionlocal-database

Database file not copied during publishing so installed application throws exception


I am developing a C# windows form application containing a service based data based. when I test my application it's database works fine but after publishing and installing the program when program tries to open sqlconnection , this error appears:

System.Data.SqlClient.SqlException (0x80131904): An attempt to attach an auto-named database for file C:\Users\Behnam\AppData\Local\Apps\2.0\Data\5XVOVXV1.3VG\M5T04ZK7.QBJ\tahl..tion_45c3791d6509222d_0001.0000_be1c7cc05811ecf0\Data\AppData\TahlilGar.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

This is my ConnectionString:

<add name="BA" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\AppData\TahlilGar.mdf;
Integrated Security=True;"providerName="System.Data.SqlClient" />

I also tried : User Instance= True; but it's result is :

The user instance login flag is not allowed when connecting to a user instance of SQL Server. The connection will be closed.

How can I fix this issue?


Edit: I checked the mentioned path and there was not my .mdf file. so i copied it from my project and it worked fine after that. now why my mdf file is not copying when publishing and installing in the expected path.


Solution

  • When using click once for publishing the windows forms application, we can include or exclude the files along with your project. MSDN link explains how to add files

    https://msdn.microsoft.com/en-us/library/kzy0fky2.aspx

    Note: Database will appear in Application Files dialog box only if it is added to project