0

I am banging my head on the wall trying to figure out how to set up my connection string for my WPF .net core 3.1 app, Everything I see says to use app.config then when I look up app.config I see use appsettings.json, neither file is natively built into the project.

I feel like I am missing a baked-in way to add and access my connection string, please advise.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
  • Username checks out – Red Sep 05 '20 at 14:52
  • Can you share your starup.cs file? – Red Sep 05 '20 at 14:57
  • .net core WPF app does not have a startup.cs @Red it isn't baked into the project. I am looking for a baked-in way to set up my connection string. – csharpnovice Sep 05 '20 at 15:19
  • https://www.c-sharpcorner.com/article/crud-operation-using-dapper-in-c-sharp/ – Red Sep 05 '20 at 15:28
  • Does this answer your question? [Cannot add appsettings.json inside WPF project .net core 3.0](https://stackoverflow.com/questions/59909207/cannot-add-appsettings-json-inside-wpf-project-net-core-3-0) – Roar S. Sep 05 '20 at 16:20

1 Answers1

0

Add app.config file and then get connectionstring with:

string GetAppSettingVal(string key)
        {
            Configuration config = null;
            string exeConfigPath = GetType().Assembly.Location;
            try
            {
                config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
            }
            catch (Exception ex)
            {
                return "";
            }

            var connectionString = config.AppSettings.CurrentConfiguration.ConnectionStrings.ConnectionStrings[key].ConnectionString; 

            if (!string.IsNullOrEmpty(connectionString))            
                return connectionString;
            
            return string.Empty;
        }
Miha
  • 1
  • 1