The documentation for ConfigurationManager.OpenExeConfiguration(string exePath)
states:
Opens the specified client configuration file as a Configuration object.
It also states that exePath
is "The path of the executable (exe) file"
The method is supposed to open the *.exe.config
file for the executable at the path specified by exePath
, and that a ConfigurationErrorsException
will be thrown if "A configuration file could not be loaded.".
The following code uses the path of a non-executable and the directory of that path contains no *.exe.config files. Yet the code executes without any exceptions, nor any other sign of an invalid argument.
var configs = Directory.GetFiles("C:\\NoConfig", "*.config");
Debug.Assert(configs.Length == 0);
File.WriteAllText("C:\\NoConfig\\notes.txt", "This is not an executable, and there is no .config file in its folder.");
var config = ConfigurationManager.OpenExeConfiguration("c:\\notes.txt");
Debug.Assert(config != null);
Yet it will now slowly become deprecated for the new .NET Core JSON based configuration, and will not be reviewed or fixed anyway.
So, is this due to a bug in this overload of the OpenExeConfiguration
method?
I just wanted a 2nd, and nth opinion before I raised it on MS Connect. And Connect is down at the moment.
ADDED: If I call OpenExeConfiguration
with a valid exePath
, to a real executable (tested), with a valid .config
file, then it reads but does not parse the file. I have to request the xml for the appSettings
section and parse it myself, using the workaround from this answer to AppSettings from custom files. This adds to my suspicion that this code is not commonly used in this mode, has been accepted as working and not reviewed, and could thus be buggy.
I'm sure it will receive scant attention with the new .NET Core configuration API replacing the old XML only one.
So you have two concerns as I understand:
OpenExeConfiguration does not fail for files with extensions other than "exe".
OpenExeConfiguration does not fail if configuration file not already exists.
I understand both points, but I'd say both of them are arguable.
Executable file does not necessary mean file with .exe extension. Yes, on Windows that's usually true, but let's take Linux for example (and we can do that because .NET is not restricted to Windows only). I can have executable .NET file with any extension (even notes.txt), or without extension at all, it doesn't matter. I can happily execute that file with "mono notes.txt" and it will run as usual.
Non existing configuration file is not an exceptional condition for Configuration
object. It even has property named HasFile
which indicates if that file exists or not. I can do the following with your code:
var config = ConfigurationManager.OpenExeConfiguration("c:\\notes.txt");
// config.HasFile == false here
config.AppSettings.Settings.Add("test", "test");
config.Save(ConfigurationSaveMode.Full, true);
// config.HasFile == true here, and file is written to disk