Just a note that I haven’t forgotten about my goal to publish my applications for X86 and X64. Here is a screenshot of the latest build of Key Manager. I am rebuilding it in WPF and will support importing keys from the old version.
Posts Tagged ‘WPF’
Key Manager 2.0
August 29th, 2008Restoring Application.LocalUserAppDataPath Functionality in .NET 3.5 / WPF
August 29th, 2008With 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; } |
