Skip to content

Using NAudio.Lame with MVC

Corey Murtagh edited this page Nov 20, 2013 · 2 revisions

This was brought to my attention by this comment on Stack Overflow.

NAudio.Lame functions by loading one of two native DLLs depending on the architecture (x86 or x64) of the executing process. These DLLs are copied to the application directory during build, which is normally sufficient to allow the system to load them.

However in the case of MVC applications, the application directory (the bin folder in your solution) is not necessarily the current directory, and so the required native DLL files cannot be located. (This is only true of native DLLs. DLLs for .NET assemblies are resolved using a different internal mechanism.)

In order for the native DLLs to be located the bin folder must be added to the PATH environment variable. One way to do this is to add the following method somewhere in your code and call it before you attempt to create an instance of LameMP3FileWriter:

	public static void CheckAddBinPath()
	{
		// find path to 'bin' folder
		var binPath = Path.Combine(new string[] { AppDomain.CurrentDomain.BaseDirectory, "bin" });
		// get current search path from environment
		var path = Environment.GetEnvironmentVariable("PATH") ?? "";

		// add 'bin' folder to search path if not already present
		if (!path.Split(Path.PathSeparator).Contains(binPath, StringComparer.CurrentCultureIgnoreCase))
		{
			path = string.Join(Path.PathSeparator.ToString(), new string[] { path, binPath });
			Environment.SetEnvironmentVariable("PATH", path);
		}
	}

This will update the PATH environment variable to include the bin folder, but only if it does not already contain that folder. After this the system will be able to locate the native DLLs in that folder.

Clone this wiki locally