Is there a way to correctly format the message string placeholders %1, %2, etc. from Win32 error strings?
The Win32Exception class returns the original Win32 message, but string.Format() only recognizes the C# placeholders like '{0}'.
Consider this example code:
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; namespace ConsoleApplication1 { [SuppressUnmanagedCodeSecurity] internal static class NativeMethods { [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr LoadLibrary(string lpFileName); } internal class Program { private static Win32Exception GetLastErrorFormatted(string argument) { var exception = new Win32Exception(); return new Win32Exception(exception.ErrorCode, exception.Message.Replace("%1", argument)); } public static IntPtr LoadLibrary(string filename) { var result = NativeMethods.LoadLibrary(filename); if (result == IntPtr.Zero) throw GetLastErrorFormatted(filename); return result; } private static void Main(string[] args) { try { LoadLibrary(@"C:\Windows\System32\eventvwr.msc"); } catch (Win32Exception e) { Console.WriteLine(e.Message); } } } }It does return the expected string "C:\Windows\System32\eventvwr.msc is not a valid Win32 application" because I manually replaced the place holder %1 with the filename. But does a .Net library function exist that can correctly format all placeholders with all its bits and pieces?