shashi sampige
shashi sampige

Reputation: 124

Change connection string during runtime

I have created wpf application using entity frame work (data first approch) now connection string was automatically created app config

But i want get connection string from text file which is placed in C Drive

Upvotes: 1

Views: 2324

Answers (3)

mohaa8844
mohaa8844

Reputation: 441

For me(I was trying to change the source of the db of data entity framework model), the fastest solution (but not risk free) was

'''

        string s = File.ReadAllText("./CheckCenter.exe.config");
        s = Regex.Replace(s, "(?<=data source=)(.*)(?=;initial catalog=)", newIp+ ",1433");
        File.WriteAllText("./CheckCenter.exe.config", s);

'''

hope its helps ^_^

Upvotes: 0

shashi sampige
shashi sampige

Reputation: 124

Replace Method1() method in context file

 public Method1()
            : base("name=DB_Entities" )
        {

        //}

With

         public Method1()

        {
            this.Database.Connection.ConnectionString = GlobalVariable.Conn;
        }

you can replace GlobalVariable.Conn with your connection srting or create Globalvaliable class file and get form it.

Upvotes: 1

Xavave
Xavave

Reputation: 695

you can change connection string at runtime like specified here: Entity Framework change connection at runtime

but you need to modify the code in the first answer of the link above:

 var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
 ? source.GetType().Name 
 : configConnectionStringName;

        // add a reference to System.Configuration
        var entityCnxStringBuilder = new EntityConnectionStringBuilder
            (System.Configuration.ConfigurationManager
                .ConnectionStrings[configNameEf].ConnectionString);

to:

 var cString = File.ReadLines(@"c:\nameofyourfilewithconnectionstring.txt").FirstOrDefault();
if (cString !=null)
{
var entityCnxStringBuilder = new EntityConnectionStringBuilder(cString);
...
}

Upvotes: 0

Related Questions