get applications appdata path without Forms-namespace

531 Views Asked by At

I would like to get the AppData path of my current application. I used to do this with Application.UserAppDataPath but it's in the System.Windows.Forms namespace and I want to get rid of that. I need it in the repository layer and its a wpf application anyway.

No more reason than to reduce the smell.

Thy and BR, Matthias

2

There are 2 best solutions below

2
Pilgerstorfer Franz On BEST ANSWER

I just had a look into the source coude of System.Windows.Forms.dll. There you can find this:

Disassembly of Application.LocaluserAppDataPath

When starting to clone this code in a class on my own I failed after having several properties, other assemblies, reflection, helper aso. So I wrote a VERY SIMPLIFIED class on my own.

    public static string LocalUserAppDataPath
    {
        get
        {
            return GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
        }
    }

    private static string GetDataPath(string basePath)
    {
        string format = @"{0}\{1}\{2}\{3}";
        string companyName = "YOUR_COMPANYNAME";
        string productName = "PRODUCTNAME";
        string productVersion = "PRODUCTVERSION";
        object[] args = new object[] { basePath, companyName, productName, productVersion };
        string path = string.Format(CultureInfo.CurrentCulture, format, args);

        return path;
    }

I know that there are some hardcoded strings. But right now, refering to your given limitations, I would give this code a try.

1
nicoh On

Maybe you can try it with SpecialFolder?

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

or

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);