Datadirectory C#

Asked

Viewed 1,049 times

0

I need a flexible connection string so that it automatically searches the program folder for file . mdf.

My following code is like this:

public Form1()
    {
        string relative = @"..\..\Database1.mdf";
        string absolute = System.IO.Path.GetFullPath(relative);
        AppDomain.CurrentDomain.SetData("DataDirectory", absolute);
        InitializeComponent();
        MessageBox.Show(absolute);
        SqlConnection conex = new SqlConnection(absolute);
    }

The variable Absolute on MessageBox works perfectly, gives the exact location of my file .mdf. But when placing in the parameter sqlConnection, generates a error:

The boot chain format does not conform to the specification initiated in index 0.

In the app.config file of the program folder I also edited for something like this:

connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Initial Catalog=Cos;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

So the only problem is that I can’t use the variable Absolute as a parameter in the method SqlConnection.

  • related to the theme: http://answall.com/questions/156488/comorprepare-programa-parausage

1 answer

1


The constructor of the Sqlconnection class takes the entire Connectionstring as its parameter. Not only the location of the database.

You have already tried concatenating the file path into the Connection string and passing it to the constructor?

For example, maybe something like this:

public Form1()
{
    string relative = @"..\..\Database1.mdf";
    string absolute = System.IO.Path.GetFullPath(relative);
    AppDomain.CurrentDomain.SetData("DataDirectory", absolute);
    InitializeComponent();
    MessageBox.Show(absolute);

    // Buscar a connection string já concatenada com o caminho:
    var connectionString = GetConnectionString(absolute);
    MessageBox.Show(connectionString);

    SqlConnection conex = new SqlConnection(connectionString);
}

public string GetConnectionString(string absolutePath)
{
    return string.Format("Data Source=(LocalDb)\v11.0;AttachDbFilename={0};Initial Catalog=Cos;Integrated Security=True;MultipleActiveResultSets=True", absolutePath);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.