Exception Was Thrown by the Target of an Invocation - Visual Studio and SQL Server Management Studio

Issue

Upon launching Visual Studio or SQL Server Management Studio, you get the error message "Exception Was Thrown by the Target of an Invocation".

Cause

The PATH environment variable on your system exceed 2048 characters.

Resolution

Many of the entries in your PATH variable contain long path names. You can convert them to short path names in one of two ways.

1. Use the dir /ad/x command to recursively determine the equivalent short path names

2. Use the C# code below -- specifically the PathConverter.GetShortPathNames method.

using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace ShortPathConverter
{
    internal class PathConverter
    {
        public static String GetShortPathName(String longPath)
        {
            StringBuilder shortPath = new StringBuilder(longPath.Length + 1);

            if (0 == PathConverter.GetShortPathName(longPath, shortPath, shortPath.Capacity))
            {
                return longPath;
            }

            return shortPath.ToString();
        }

        // This method can shorten your PATH environment variable
        public static String GetShortPathNames(String longPathNames, String delimiter = ";")
        {
            var items = longPathNames.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            var longPaths = items.Select(o => o.ToLowerInvariant())
                                .Distinct()
                                .Select(o => PathConverter.GetShortPathName(o))
                                .ToList();

            return string.Join(";", longPaths);
        }

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);
    }
}