2

In my MVC Application I use the connection string is set in the Web.config via

Private connectionString As String = ConfigurationManager.ConnectionStrings("DBCS").ConnectionString

and have no problems with my db connection. But since I need a password and username to log into my database I hardcoded that in the web.config

<connectionStrings>
    <add name="DBCS" connectionString="server=win\SQLExpress;database=myDb; uid=myUsername;password=myPassword" providerName="System.Data.SqlClient" />
  </connectionStrings>

I am looking for a way to send the password and username from the userinterface to the config.web file first off I thought the ConfigurationManager Class should provide a property for that but I cannot find something. Can anyone explain to me how to do this?

ekad
  • 14,436
  • 26
  • 44
  • 46
ruedi
  • 5,365
  • 15
  • 52
  • 88
  • http://stackoverflow.com/questions/2260317/change-a-web-config-programmatically-with-c-sharp-net or create connection https://msdn.microsoft.com/en-us/library/ms136093.aspx – Zaki Apr 29 '15 at 11:38

1 Answers1

8

You can save this value in app settings:

<appSettings>
  <add key="DBCS" value="Data Source=win\SQLExpress;Initial Catalog=myDb;User ID={0};Password={1}" />
</appSettings>

and then do the following:

using System.Data.SqlClient; 


  public void DoDatabaseOperations(string _Username, string _Password)
  {
    string connetionString = null;
    SqlConnection cnn ;
    connetionString = string.Format(ConfigurationManager.AppSettings("DBCS"), _Username, _Password);
    cnn = new SqlConnection(connetionString);
    try
    {
        cnn.Open();

        // your code here

        cnn.Close();
    }
    catch (Exception ex)
    {
        // handle exception
    }
  }

VB.NET Equivalent:

Imports System.Data.SqlClient

Public Sub DoDatabaseOperations(_Username As String, _Password As String)
    Dim connetionString As String = Nothing
    Dim cnn As SqlConnection
    connetionString = String.Format(ConfigurationManager.AppSettings("DBCS"), _Username, _Password)
    cnn = New SqlConnection(connetionString)
    Try
        cnn.Open()

        ' your code here

        cnn.Close()
            ' handle exception
    Catch ex As Exception
    End Try
End Sub
enb081
  • 3,831
  • 11
  • 43
  • 66