Vigneshwaran
Vigneshwaran

Reputation: 397

How can I change my connectionString in app.config file at runtime?

I created my vb.net project to .exe file. During installation on another machine, one can change the location of installing package to any drive. In my project, I have set my app.config to point the Database that is available in c:\project. If I suppose, while installation, when I change the location of installation to **d:** or anywhere, I get invalid access db. What I want is:

I want to reconfigure my app.config file automatically, by detecting its current db location.

Upvotes: 1

Views: 15588

Answers (4)

Jonathan Ismaila
Jonathan Ismaila

Reputation: 1

You have three options: 1.) Create and use a folder in C:\Databse and set your connection string at design time.

2.)Add the database to the project's data source at design time, then use '|Data Directory|\mydb.mdb' as your connection string.

3.) And if you use sqlserver, you don't need to worry about the location of the database once you have attached the database to sqlserver. You only need to use the proper connection string eg 'Data Source=.; Database = mydb; Integrated Security = False; Username=myusername; Password = mypassword; User Instance = false'. The above is an example of a sql server with SQL Authentication mode as login, if you use Windows Authentication, set Integrated Security = True and remove both username and password.

Upvotes: 0

athiq bari
athiq bari

Reputation: 1

simple...

    MsgBox(My.Settings.Item("remoteAddress").ToString)
    My.Settings.Item("remoteAddress") = "abcserver.servebbs.net"
    My.Settings.Save()
    MsgBox(My.Settings.Item("remoteAddress").ToString)

Upvotes: 0

Carlos Landeras
Carlos Landeras

Reputation: 11063

Imports System.Configuration
Imports System.Configuration.ConfigurationManager

        Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)          
        config.ConnectionStrings.ConnectionStrings("MyProject.Properties.Settings.MyProjectConString").ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\SampleDB;Persist Security Info=True;"
        config.Save(ConfigurationSaveMode.Modified)

Where MyProject.Properties.Settings.MyProjectConString is the name of your project and connection string.

Upvotes: 5

Although this is too late to answer as the question is very old but I think this might help someone else in the future.

So, there is a way to change the Connection String value in the runtime. Since connection string is a read-only item like all other items that are on Application Scope under My.Settings so we can't change it using My.Setting.ConnectionString = "Something". But here is the code by which you can solve the issue and change any My.Settings item that is on Application Scope in the runtime.

So the code is,

My.Settings.Item("ConnectionString") = "Something"

Upvotes: 0

Related Questions