Search code examples
c#reflectionspecial-folders

Is there a way to access a special folder path using a special folder name as a string using C#


I have a text value from an App.Config file I read which identifies a special folder to use such as "LocalApplicationData". I would like to use this text value to access an Environment.SpecialFolder value. I have tried the below code statement but it does not work. Can someone please point out what is wrong or is there another way I should try?

object value = typeof(Environment.SpecialFolder).GetProperty("LocalApplicationData").GetValue(null);

Normally a special folder path is returned with a statement like the following:

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

This is fine if I know in advance which special folder to specify. But in this problem case, the special folder name can be several values and is read from a app.config file. This is for a WinForms application not a web application.

Thanks in advance.


Solution

  • Try:

    var s = // read value from config.  Store in string
    SpecialFolder sf;
    if( Enum.TryParse( s, true, out sf))
    {
        // success, now let's get the actual path
        var actualPath = Environment.GetFolderPath(sf)
    }