简体   繁体   中英

How do I format the Db connectionstring in my app.config file for a Windows Forms Application?

I've scoured the internet to try and configure my App.config connectionstring properly for a Windows Forms application to no avail.

Here's my first attempt at connecting my application to my database:

private static string CONNECTION_STRING =
    @"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Visual Studio 2013\Projects\Test\Test\MyDatabase.mdf;Integrated Security=True;Connect Timeout=30";

This connection string worked great when running the program on my local machine, but failed to run on any other. I figured it was because of the absolute path included in the connection string. After looking at many threads regarding the App.config file, I added the System.Configuration reference and also added the following to their appropriate sections in the Form1 and App.config code:

Inside my Form1.cs:

using System.Configuration;

private static string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;

Inside my App.config file:

  <connectionStrings>
    <add name="TestConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf" providerName="System.Data.SqlClient"/>
  </connectionStrings>

When trying to run the program, I receive the following error:

An attempt to attach an auto-named database for file D:\\Visual Studio 2013\\Projects\\Test\\Test\\bin\\Debug\\MyDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

I've read that the |DataDirectory| included in the connectionString is only for Web apps, but I've also read comments from users that had success in their Windows Apps using it just as I tried to.

What am I missing here? How do I set up my connectionString in my App.config file such that this application will still access the database, regardless of which machine I run the executable from?

Thank you for any help!

In general |DataDirectory| works well for WinForms applications. I just tried it on my local machine and it was OK.

Maybe your mdf database file is not in the root folder? I created a new folder named Data, moved mdf file there and was able to get exactly the same exception as you have.

So in my case changing connectionString param to this one solved the problem:

AttachDbFileName=|DataDirectory|\Data\Database1.mdf;

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