Search code examples
c#.netformsappdatauserappdatapath

get applications appdata path without Forms-namespace


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


Solution

  • 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.