Posts Tagged ‘Application’

Restoring Application.LocalUserAppDataPath Functionality in .NET 3.5 / WPF

August 29th, 2008

With the arrival of .NET 3.5 and consequently WPF applications, Microsoft has done away with the old Application WinForms class. No longer can you call Application.LocalUserAppDataPath to get where the user’s files are stored. To restore this functionality as well as add a bit more, I have tapped into an uncommon resource: extension methods. Let’s dig a little deeper, shall we?

The first thing we need to do is be able to get the Company Name from the assembly. Inside of a blank static class, add the following functions. I have named my class ApplicationExtensions.

Fortunately the company name is kept in an attribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static string GetCompanyName(this Assembly assembly)
{
    string name = string.Empty;
 
    object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
 
    if (attributes != null && attributes.Length > 0)
    {
        AssemblyCompanyAttribute aca = attributes[0] as AssemblyCompanyAttribute;
 
        if (aca != null)
        {
            name = aca.Company;
        }
    }
 
    return name;
}

Note my lack of any formal error handling. I will leave this up to you to handle. For now, returning an empty string will do. Next up, we need to be able to format the version number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static string GetFormattedVersion(this Assembly assembly)
{
    string version = string.Empty;
 
    try{
        Version assemblyVersion = assembly.GetName().Version;
 
        version = string.Format("{0}.{1}.{2}.{3}",
            assemblyVersion.Major,
            assemblyVersion.Minor,
            assemblyVersion.Build,
            assemblyVersion.Revision);
    }
    catch{}
 
    return version;
}

And finally, the LocalUserDataPath:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static string GetLocalUserAppDataPath(this Application application)
{
    string path = string.Empty;
 
    Assembly assembly = Assembly.GetEntryAssembly();
 
    if (assembly != null)
    {
        path = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            Path.Combine(
                Path.Combine(
                    assembly.GetCompanyName(),
                    assembly.GetName().Name),
                assembly.GetFormattedVersion()
                )
            );
    }
 
    return path;
}