private static unsafe Icon ExtractAssociatedIcon(string filePath, int index) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } filePath = Path.GetFullPath(filePath); if (!File.Exists(filePath)) { throw new FileNotFoundException(message: null, fileName: filePath); } // ExtractAssociatedIcon copies the loaded path into the buffer that it is passed. // It isn't clear what the exact semantics are for copying back the path, a quick // look at the code it might be hard coded to 128 chars for some cases. Leaving the // historical MAX_PATH as a minimum to be safe. char[] buffer = ArrayPool <char> .Shared.Rent(Math.Max(NativeMethods.MAX_PATH, filePath.Length)); filePath.CopyTo(0, buffer, 0, filePath.Length); buffer[filePath.Length] = '\0'; fixed(char *b = buffer) { IntPtr hIcon = SafeNativeMethods.ExtractAssociatedIcon(NativeMethods.NullHandleRef, b, ref index); ArrayPool <char> .Shared.Return(buffer); if (hIcon != IntPtr.Zero) { return(new Icon(hIcon, true)); } } return(null); }