C#- How to use OpenFileDialog to load a ConfigurationUserLevel file?

45 views Asked by At

I want to be able to load a config file (.config) of type System.Configuration.ConfigurationUserLevel using OpenFileDialog.

I need the file to be a ConfigurationUserLevel because the I need to use .AppSettings, as its functionality already exists in many other places throughout my code.

Currently I have,

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var extension = Path.GetExtension(openFileDialog1.FileName);
    if(extension.Equals(".config"))
    {
        try
        {
            var configFile = (ConfigurationUserLevel)openFileDialog1.OpenFile();
            var settings = configFile.AppSettings.Settings;

but I get an error saying that I cannot simply convert from a Stream to ConfigurationUserLevel.

Is there a way for me to get a ConfigurationUserLevel file from an openFileDialog? Or is there a workaround?

1

There are 1 answers

0
Kangjun Heo On

OpenFileDialog just helps users to get FileName, of course you can't open file directly with openFiledialog.OpenFile().

You need to read file with FileName from OpenFileDialog, and parse it then cast to ConfigurationUserLevel.

This can be help: https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx