home » knowledge base » Getting user-specific application data directory for .NET WinForms apps (2006-01-01)

Tags: .net (2) c# (2) code snippet (6) windows (8) winforms (1)

Getting user-specific application data directory for .NET WinForms apps

Windows defines a number of directories for specific things.

One of those directories is a directory that a well-behaved Windows application should use to store user-specific data (e.g. a list of recently open documents by this user, customization information etc.).

Usually this is a hidden directory C:\Documents and Settings\$UserName\Application Data. Most applications choose to create a sub-directory named after application. Bigger companies, like Macromedia or Microsoft choose, to use 2-level hierarchy: $CompanyName\$ApplicationName.

In .NET framework, Application object (from System.Windows.Forms namespace) has a static property UserAppDataPath that returns a string naming directory for storing user-specific application data. However, designers went overboard and used 3-level hierarchy: $CompanyName\$ApplicationName\$VersionNumber.

Adding version number is a mistake. When user upgrades the application, he doesn't want to loose his settings and customizations.

The following static function rectifies this problem. It returns a base name of the user application data directory by stripping last 3 components from UserAppDataPath.

class Util
{
    static string cachedUserDataPath;
    // return a directory where we store per-user app data (like serialized settings)
    static public string GetUserDataPath()
    {
        if (null != cachedUserDataPath) return cachedUserDataPath;
        cachedUserDataPath = System.IO.Path.Combine(System.Windows.Forms.Application.UserAppDataPath, "CamViewer");
        string[] pathParts = cachedUserDataPath.Split(System.IO.Path.DirectorySeparatorChar);
        System.Diagnostics.Debug.Assert(pathParts.Length > 3);
        string pathSep = System.Char.ToString(System.IO.Path.DirectorySeparatorChar);
        if (pathParts.Length > 3)
            cachedUserDataPath = System.String.Join(pathSep, pathParts, 0, pathParts.Length - 2);
        return cachedUserDataPath;
    }
}
Tags: .net (2) c# (2) code snippet (6) windows (8) winforms (1)


Krzysztof Kowalczyk