DataDirectory C #

0

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

My following code looks 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 absolute variable when displayed in MessageBox works perfectly, gives the exact location of my .mdf file. But setting the sqlConnection parameter generates an error :

  

The format of the boot string does not conform to the specification started at 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 not use the absolute variable as a parameter in the SqlConnection method.

    
asked by anonymous 04.10.2016 / 05:44

1 answer

1

The constructor of the SqlConnection class receives the entire ConnectionString as a parameter. Not just the location of the bank.

Have you tried concatenating the file path in 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);
}
    
18.10.2016 / 14:36