Copying/creating .mdf files in SQL Server folder during setup of C# windows application

StackOverflow https://stackoverflow.com/questions/15972657

  •  03-04-2022
  •  | 
  •  

Is it possible to copy my database files i.e .mdf files to a destination folder which is my SQL Server folder during setup of my windows C# application?

Also, how do I attach those filed to the database of sql server automatically in setup?

有帮助吗?

解决方案

You can use an attached database for your application. This will help you in creating setup for that.

  1. Add a folder named ”DB” to the project, and copy the database file into it after you detach it from your SQL Server.

  2. Change your connection string like this:

    <connectionStrings>
        <add name="WindowsFormsApplication1.Properties.Settings.BabakConnectionString"
            connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\DB\Babak.mdf;
            Initial Catalog=test;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    
  3. After these, the database file will auto attach to the SQL Server when you run your application, and the database name is “test”. you can open SQL Server Management Studio to find it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top