How do I get the .NET Framework directory?
Let's look at several ways to slice this one:
Hard code the path
This method is fragile and involves knowing the several things not least the version of the Framework. If you were looking for simplicity, say in the WiX configuration file, you might go with this. Otherwise, there are much better options available.
If you're in ASP.NET or otherwise already have a reference to System.Web.dll, you may want to use the HttpRuntime.ClrInstallDirectory property. Otherwise, this may not be worth loading yet another assembly.
The GetCORSystemDirectory method, in mscoree.dll, returns the fully qualified installation dir of .NET Framework loaded into the current process.
HRESULT GetCORSystemDirectory ( LPWSTR pbuffer, DWORD cchBuffer, DWORD* dwlength );
pbuffer - [out] Buffer in which the runtime returns a string containing the fully qualified name of the installation directory of the runtime
cchBuffer - [in] the size in bytes of pbuffer
dwlength - [out] The number of chars returned in pbuffer
Of course, if your managed code file needs this info, you'll need p/invoke.
My personal favorite. The RuntimeEnvironment class is in the System.Runtime.InteropServices namespace. I'd use RuntimeEnvironment.GetRuntimeDirectory() simply for elegant, readable and maintable code. Plus, it is in mscorlib.dll.
This post is by no means comprehensive. If you know of a better way to do this, please drop a comment.
Tags: NetFX, CLR, How to