none
Cannot read (database connection string from ) App.config file in .exe file and getting error object reference not set to be an instance RRS feed

  • Question

  • Hi team,

    I am working a console application . i have build the application and taken .exe file from debug folder.

    i have set data base connection string in app.config folder.

    through debug it is working and connecting to database table and it is updating based on code.

    But after i given .exe file (debug folder) to testing team they are failing to get the updated data and application is crashing, error is Object reference not set to be an instance of an object. error.

    kinldy help me ...  where can i add to get directly read through exe.

    Thanks Team.

    Anil


    Friday, February 28, 2020 7:27 AM

All replies

  • Hi Anil,

    Thank you for posting here.

    Please note that App.Config is located at the root of the project.

    If you only give the debug folder to the testing team, it means that they do not have the App.config file.

    By the way, for your privacy and security, please do not post your private information such as account, password, personal phone number, and email address on the forum.

    Thanks for your understanding.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, February 28, 2020 9:02 AM
  • hello friend

    When create setup file all the dependcies copy to the setup folder.

    But when taken the debug folder all the dependencies not taken .

    1- try to add references to your project from the exsting degug folder .

    2- I suspect you are taken some rererence from out side the debug folder .

    3-try to figure out the .net framework you use at developement ,that is installed there.

    Friday, February 28, 2020 9:24 AM
  • Hello,

    Can you post the contents of the config file that is copied along with the executable here and the code that accesses the connection string ?

    I would expect to see

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
        </configSections>
        <connectionStrings>
            <add name="ConnectionString" 
                 connectionString="Data Source=KARENS-PC;Initial Catalog=NorthWindDemo;Integrated Security=True" />
        </connectionStrings>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
        </startup>
    </configuration>

    using System;
    using System.Configuration;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(ConfigurationManager
                    .ConnectionStrings["ConnectionString"].ConnectionString);
    
                Console.ReadLine();
            }
        }
    }
    

    The same would be true if the database resided in the app folder be it the debug folder or the folder you copied the executable and config file.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, February 28, 2020 10:42 AM
    Moderator
  • i have build the application and taken .exe file from debug folder.

    Remember that there is a second thing that you also have to take from the Debug folder: The file that ends in .exe.config.

    When you compile, the app.config from the source code folder is copied into youraplication.exe.config in the binaries folder (Debug or Release depending on how you are compiling). This .exe.config file is the one that is read at runtime.

    If the file is not present at runtime, the ConfigurationManager class will return null when reading your connection string. If the program then tries to access any methods on the returned value and you have not written an "if" condition to cover for this case, then you get the "object not set..." exception.

    Saturday, February 29, 2020 12:17 PM
    Moderator
  • The app.config is only used in VS debug mode. On the successful compile of a project that creates an program.exe, a second file is crated call program.exe.config that is a copy of the app.config that is sitting in the bin folder too with the program.exe file, which is the runtime config. .NET runtime is looking for the program.exe.config file,  and you must copy the program.exe and the program.exe.config files to the same location for deplyment. 
    • Edited by DA924x Saturday, February 29, 2020 1:32 PM
    Saturday, February 29, 2020 1:31 PM
  • The app.config is only used in VS debug mode 

    No, it's not used even in debug mode. When you are debugging, the settings are actually read from the program.exe.config in the debug folder, not from the app.config.

    You can verify this by setting a breakpoint in the source code before the first setting is read from the .config. While the debugger is stopped there, go to the filesystem and edit one of the two .config files so that they don't contain the same value. Then go back to the debugger and advance past the point where the setting is read from the file. You will see that the value returned is the one that you wrote in program.exe.config, and not the one from app.config. Note: you have to perform the edit before the first access to the .config is done, because it is cached in memory by the configuration manager, so if you edit it later the program is still going to return the "old" value that was there the first time.

    Saturday, February 29, 2020 5:58 PM
    Moderator
  • No, it's not used even in debug mode. When you are debugging, the settings are actually read from the program.exe.config in the debug folder, not from the app.config.

    No what you are saying is  not fully correct. Yes at the root project the runtime exe.config will always be used even in a Web program with its root Web config.

    But if one is doing integration testing using a test harness such a MSTest or Resharper as an example that is hosting the Integration test classlib project, then any config info must be in the app.config for the test project so that .NET can find it. It doesn't even matter that the test harness is running the test classlib  project in VS debug mode either. It's going to use the app.config at the project level for the classlib project being hosted by a test harness.

    Saturday, February 29, 2020 9:15 PM
  • Adding to the mix about a config file, when settings change they are set to a user config file, the following code shows how to gain access if it exists.

    public class ConfigurationSettings  
    {
        public static string ConfigurationFolder
        {
            get
            {
                var config = ConfigurationManager
                    .OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                return config.FilePath.Replace("\\user.config", "");
            }
        }
    
        public bool ConfigurationFolderExists => Directory.Exists(ConfigurationFolder);
    
        public static string ConfigurationFile() => 
            Path.GetFileName(ConfigurationManager
                .OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath);
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, February 29, 2020 11:18 PM
    Moderator
  • Adding to the mix about a config file, when settings change they are set to a user config file, the following code shows how to gain access if it exists.

    I have only seen the user.config used in the root web.config where the path is given to the user.config, which automatically includes the content of the user.config in the Web.config.

    But on the other hand and in deployment of an exe with its accompanying exe.config, the software developer must understand that both files must be deployed to the same location so that the runtime can find the runtime config. Adding a user.config into this is just more complications, IMO.

    Sunday, March 1, 2020 12:02 AM
  • Let's say I have a setting called Test which resides in the config file, when changed it is saved to a folder like this. Works for console and desktop apps.

    C:\Users\UserName\AppData\Local\Microsoft\AppName.exe_Url_qkocfvuzxvqvi4ll3wnpd0hv5ldrzv1a\1.0.0.0

    Properties.Settings.Default.Test = "Karen";
    Properties.Settings.Default.Save();

    This does not affect a connection string as it's application level scope while the latter is user level scope.

    This change would not be reflected in user.config but the runtime app.config.

    private static void Demo()
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
        config.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString = 
            "Data Source=.\\SQLEXPRESS;Initial Catalog=NorthWind;Integrated Security=True";
    
        config.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");
    }
    When I was developing for desktop I never used Settings, used json files instead.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, March 1, 2020 1:40 AM
    Moderator