@@ -2055,7 +2055,7 @@ private static Exception ToPythonException(Exception e, string? filename = null)
20552055 return PythonOps . OSError ( errorCode , message , filename , errorCode ) ;
20562056 }
20572057
2058- return PythonExceptions . CreateThrowable ( PythonExceptions . OSError , errorCode , message ) ;
2058+ return PythonOps . OSError ( errorCode , message , filename ) ;
20592059 }
20602060
20612061 private static Exception ? IOExceptionToPythonException ( IOException ? ioe , int error , string ? filename ) {
@@ -2214,29 +2214,22 @@ private static Exception GetUnixError(int error, string? filename = null, string
22142214 return PythonOps . OSError ( error , msg , filename , null , filename2 ) ;
22152215 }
22162216
2217- [ DllImport ( "kernel32.dll" , EntryPoint = "FormatMessageW" , SetLastError = true , CharSet = CharSet . Unicode , BestFitMapping = true ) ]
2218- private static extern int FormatMessage ( int dwFlags , IntPtr lpSource ,
2219- int dwMessageId , int dwLanguageId , [ Out ] StringBuilder lpBuffer ,
2220- int nSize , IntPtr arguments ) ;
2217+ #endif
22212218
2222- private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200 ;
2223- private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000 ;
2224- private const int ERROR_INSUFFICIENT_BUFFER = 0x7A ;
2219+ #if FEATURE_NATIVE || FEATURE_CTYPES
22252220
22262221 // Gets an error message for a Win32 error code.
22272222 internal static string GetMessage ( int errorCode ) {
2228- var buf = new StringBuilder ( 256 ) ;
2229- int msgLen = 0 ;
2230- int lastError = ERROR_INSUFFICIENT_BUFFER ;
2231- while ( msgLen == 0 && lastError == ERROR_INSUFFICIENT_BUFFER ) {
2232- msgLen = FormatMessage ( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , IntPtr . Zero , errorCode , 0 , buf , buf . Capacity , IntPtr . Zero ) ;
2233- if ( msgLen == 0 ) {
2234- lastError = Marshal . GetLastWin32Error ( ) ;
2235- if ( lastError == ERROR_INSUFFICIENT_BUFFER )
2236- buf . Capacity *= 2 ;
2237- }
2238- }
2239- return buf . ToString ( ) . TrimEnd ( '\r ' , '\n ' , '.' ) ;
2223+ string msg = new Win32Exception ( errorCode ) . Message ;
2224+ // error codes: https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes
2225+ if ( errorCode is not ( < 0 or >= 8200 or 34 or 106 or 317 or 718 ) ) {
2226+ msg = msg . IndexOf ( '%' ) switch {
2227+ 0 => "The file specified" + msg . Substring ( 2 ) ,
2228+ > 0 => msg . Replace ( "%1" , "the file specified" ) ,
2229+ _ => msg
2230+ } ;
2231+ }
2232+ return msg . TrimEnd ( '\r ' , '\n ' , '.' ) ;
22402233 }
22412234
22422235 internal static Exception GetLastWin32Error ( string ? filename = null , string ? filename2 = null )
0 commit comments