简体   繁体   中英

Access App.Config File from a C# Assembly called by an executable

Is it possible to access an App.Config File from a C# Class Library that is called from an exe?

We are running into error's and getting null when we try access the config file? I presume its to do with the originator of the call on the library, is there a work around to this other than hard coding to the file system in the Class Library?

       try
        {
            string cleanupScripts = string.Empty;
            cleanupScripts = ConfigurationManager.AppSettings["CleanupScripts"];

            if (cleanupScripts == null)
            {
                throw new System.ApplicationException("Null was returned");
            }
        }
        catch (Exception ex)
        {
            throw (ex); 

        }

Cheers

When reading app config values from a class library function, it is the app.config of the exe that is read. The general idea is that each client using a library should supply the relevant configuration itself. So if you have an app.config in your class library project, that one will never be read.

Not sure if you can do this, but I am pretty sure that C# Class Libraries allow you to use Resources. I think its probably best for you to store the App.Config as a Resource and then access you App.config from the Resource.

But I guess the question is, why are you storing Configuration items inside a DLL? why don't you create constructors on your library and have your configuration in the UI that is calling your C# Class library.

when deployed app.config files are copied as ProjectName.exe.config. You should be reading this file from the class library.

Hope that I understood the question correctly

Thanks Goku

It's easy:

First you go in the properties of your C# project

在此处输入图像描述

Then to the paraméters tab

在此处输入图像描述

Then you click to create parameters, you choose a name, a type, value, scope

在此处输入图像描述

It creates an XML file name YourEXEFile.config in the bin folder. Then you can use it in your code. Or you can modify it outside your code.

static void Main(string[] args)
{
  string myP = Properties.Settings.Default.myParam1;

  Console.WriteLine(myP);
}

You can modify it in your project:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM