views:

265

answers:

2

I apologize as this question is somewhat basic; however, after a great deal of searching, I have not found a suitable answer. I am building a windows forms application and need to reference an app.config file for the location to a data file. Before calling

XElement xml = XElement.Load(ConfigurationManager.AppSettings["EntityData"].ToString());

I want to ensure that the app.config file exists. I have tried multiple methods but it seems that it is a lot more work then it should be. For example I have been trying to use the following code to determine the path for the file

        Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
        string fullConfigurationFilename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(uri.AbsolutePath), configurationFilename);

but I run into issues with spaces in the path. Is there a better way to check for the existence of the app.config, do I even need to check?

Thank you

A: 

System.Configuration should do all of this work for you. There shouldn't be a need to manually load a config file.

Jason
+1  A: 

I don't think you need to verify that the config file exists. The following code should work without exceptions:

string temp = ConfigurationManager.AppSettings["EntityData"];
if (temp != null)
{
    XElement xml = XElement.Load(temp);
}

Note that AppSettings will return a string if the key is found, so you don't need to call ToString to convert it. If the key does not exist, you should instead get a null reference that you can test for.

Fredrik Mörk
An exception occurs if the config file is not there. I can handle the exception, but it seems like a more robust solution would ensure that it is there before relying on the exception handling.
Irwin M. Fletcher
@lansinwd: are you sure? I tried out the above code both with the config file not being preset, the file existing but without an `appSettings` section and with the `appSettings` section present but without the key in question. In none of these cases did it throw an exception but rather just returned `null`. I made these tests in a Console application; perhaps other application types results in different behavior.
Fredrik Mörk
Thanks for writing back. I tried this on a pc last night on a windows forms application (C#) in VS2005 and did not recieve any exceptions. However, when I tried it again today in VS2008, it threw an exception when I deleted the config file and ran the executable.
Irwin M. Fletcher
@Fredrik Mork - You are correct, after reviewing my code the exception was coming from a later section in the code. It would seem checking for the existence of the app.config is not needed
Irwin M. Fletcher