Search code examples
c#.netwebclientapp-confignetworkcredentials

Embed credentials for webclient in C# Console Application app.config?


Currently I'm using a login method like this to login, but I want to embed this into the app.config file for safe keeping...

Currently it looks like this.

WebClient c = new WebClient();  
c.Credentials = new System.Net.NetworkCredential("UN", "PW", "server");

How can I embed this into the app.config file???


Solution

  • <appSettings>
      <add key="NetworkCredentialUserName" value="UN" />
      <add key="NetworkCredentialPassword" value="PW" />
    </appSettings>
    

    Then

    var networkCredentialUserName = ConfigurationManager.AppSettings["NetworkCredentialUserName"];
    var networkCredentialPassword = ConfigurationManager.AppSettings["NetworkCredentialPassword"];
    c.Credentials = new System.Net.NetworkCredential(networkCredentialUserName, networkCredentialPassword , "server");
    

    This however does not make them secure. If the network credential username & password are sensitive, I would consider encrypting the app.config appSettings section using something like PKCS12ProtectedConfigurationProvider (a nuget package).