简体   繁体   中英

Browsing datadirectory for SQL Server database does not work

I have hardcoded the data directory for the database. Since I want to avoid it, I have decided to use the FolderBrowserDialog and store the dialog string into the application settings.

This is the hardcoded code snippet, which can open the SQL connection:

AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\Users\Osman\Documents\Visual Studio 2013\Projects\CompanyWPF\CompanyWPF\");

try
{
    using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
    {
        con.Open();
    }
}
catch (Exception ex)
{
    MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

But when I'm using the stored string from the application settings:

AppDomain.CurrentDomain.SetData("DataDirectory",@"" + Properties.Settings.Default.ConnectionString);

try
{
    using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=@|DataDirectory|\Produkt.mdf;Integrated Security=True") )
    {
        con.Open();
    }
}
catch (Exception ex)
{
    MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

then the following error occurs:

Invalid value for key 'attachdbfilename'.

I have set a breakpoint, and the stored string from the application setting has the value:

C:\\Users\\Osman\\Documents\\Visual Studio 2013\\Projects\\CompanyWPF\\CompanyWPF\\

I do not sure what you are going to do but i think here is the problem

            using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=@|DataDirectory|\Produkt.mdf;Integrated Security=True") )

Use This Instead

using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True") )

Note : Remove @ From this "@|DataDirectory| "

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