0

I am using the following connection string in my c# application to communicate to my database which is hosted locally.

string conn = String.Format("Server={0};Port={1};" +
                                "User Id={2};Password={3};Database={4};",
                                "localhost", "5432", "postgres",
                                "postgres", "table");
NpgsqlConnection connection = new NpgsqlConnection(connstring);
connection.Open();
NpgsqlCommand sqlcmd = new NpgsqlCommand("SELECT * FROM public.roads", connection);
NpgsqlDataReader r = sqlcmd.ExecuteReader();

Is there a way I can add the server information in config.app file and access it in my code?

5
  • Possible duplicate of How to use Entity Framework + PostgreSQL from connection? Commented Jun 20, 2018 at 5:39
  • Saw the link earlier but couldn't relate it to my problem. Commented Jun 20, 2018 at 5:45
  • 2
    yes add that in app.config or web.config file. And access that by configuration manager Commented Jun 20, 2018 at 5:48
  • @BhubanShrestha thanks for your comment. Can you provide me with a link or any resource related to this. I am new to c# development. Commented Jun 20, 2018 at 5:51
  • 1
    connectionstrings.com/store-connection-string-in-webconfig You need to add reference to configuration manager to access connection string in config file Commented Jun 20, 2018 at 5:54

1 Answer 1

1

Check out Connection Strings and Configuration Files.

In the app/web.config:

<configuration>
  <configSections>
  (...)
  <connectionStrings>
    <add name="Name1" connectionString="..." />
  </connectionStrings>

In the code:

var connectionString = ConfigurationManager.ConnectionStrings["Name1"].ConnectionString;

Please note that the benefit of using connectionStrings section and not the appSettings is that if you're using an object-relational mapping framework there may be a support for using the connection string by name.

e.g.

public class RepositoryContext: DbContext
{
    public RepositoryContext() : base("Name1") 
    {
        (...)
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Had to add {using System.Configuration;} in start and it worked like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.