Get Win32 Error Message C#
Contents |
Farkas - MSSeptember 10, 20045 0 0 0 If you ever need to P/Invoke to an API that returns extended error information via the GetLastErrorfunction, then you've also probably been through the pain of converting the error code marshal getlastwin32error c# into a usable error message via the FormatMessage API … not exactly marshal.getlastwin32error error codes one of the more user-friendly APIs for managed code callers. Thankfully, there's a shortcut way to get this message, getlastwin32error codes exposed through the Win32Exception class. Simply doing this: string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Will prevent you from needing to call FormatMessage to get an error message for an error code. Of c# win32 error codes course you also need to remember to set the SetLastError named parameter on your DllImport attribute to true,and obtain the error code through a call to Marshal.GetLastWin32Error, since P/Invoking to GetLastError directly will generally not work (since the last error may have been set again by another API that the CLR has called). If you're using VB.Net, Err.LastDllError is also an acceptable
C# Getlasterror Example
way of accessing the last error code. Tags Windows Comments (5) Cancel reply Name * Email * Website Evgeny M says: September 12, 2004 at 1:15 am Something in the area, related to ComExceptions. To retrieve hresult from com exception use: uint HResult = (uint)Marshal.GetHRForException(ex); Reply Richard says: July 28, 2005 at 11:13 am Actually, you can simplify the call to: string errorMessage = new Win32Exception().Message; The default constructor for the Win32Excpeption calls Marshall.GetLastWin32Error for you. Reply Shawn Farkas - MS says: July 28, 2005 at 8:28 pm Good point Richard -- thanks for the tip. -Shawn Reply jholder says: January 5, 2007 at 1:06 am One good thing I wanted to point out about writing it this way (at least for learning purposes): string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; is that it is obvious I can stick an int in there and get out the message: int errcode = somefunction(); string errorMessage = new Win32Exception(errcode).Message; Just a quick observation. Reply Dan Ware says: March 26, 2009 at 8:37 am You can also get more info about a COMException as it has an error code; T
resources
C# Getlastwin32error
Windows Server 2012 resources Programs MSDN c# system error codes subscriptions Overview Benefits Administrators Students Microsoft Imagine Microsoft Student Partners win32exception ISV Startups TechRewards Events Community Magazine Forums Blogs Channel 9 Documentation APIs and reference Dev centers https://blogs.msdn.microsoft.com/shawnfa/2004/09/10/formatmessage-shortcut-for-win32-error-codes/ Retired content Samples We’re sorry. The content you requested has been removed. You’ll be auto redirected in 1 second. System.Runtime.InteropServices Marshal Class Marshal Methods Marshal Methods GetLastWin32Error Method GetLastWin32Error Method GetLastWin32Error Method https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getlastwin32error(v=vs.110).aspx AddRef Method AllocCoTaskMem Method AllocHGlobal Method AreComObjectsAvailableForCleanup Method BindToMoniker Method ChangeWrapperHandleStrength Method CleanupUnusedObjectsInCurrentContext Method Copy Method CreateAggregatedObject Method CreateWrapperOfType Method DestroyStructure Method FinalReleaseComObject Method FreeBSTR Method FreeCoTaskMem Method FreeHGlobal Method GenerateGuidForType Method GenerateProgIdForType Method GetActiveObject Method GetComInterfaceForObject Method GetComInterfaceForObjectInContext Method GetComObjectData Method GetComSlotForMethodInfo Method GetDelegateForFunctionPointer Method GetEndComSlot Method GetExceptionCode Method GetExceptionForHR Method GetExceptionPointers Method GetFunctionPointerForDelegate Method GetHINSTANCE Method GetHRForException Method GetHRForLastWin32Error Method GetIDispatchForObject Method GetIDispatchForObjectInContext Method GetITypeInfoForType Method GetIUnknownForObject Method GetIUnknownForObjectInContext Method GetLastWin32Error Method GetManagedThunkForUnmanagedMethodPtr Method GetMethodInfoForComSlot Method GetNativeVariantForObject Method GetObjectForIUnknown Method GetObjectForNativeVariant Method GetObjectsForNativeVariants Method GetStartComSlot Method GetThreadFromFiberCookie Method GetTypedObjectForIUnknown Method GetTypeForITypeInfo Method Ge
Ask a Question Need help? Post your question and get tips & solutions from a community of 418,553 IT Pros & Developers. It's quick & https://bytes.com/topic/c-sharp/answers/225714-how-do-you-get-text-description-last-win32-error easy. How do you get a text description of the last Win32 error? P: http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/CompMod/System/ComponentModel/Win32Exception@cs/1/Win32Exception@cs n/a Will Pittenger I see System.Runtime.InteropServices.Marshal.GetLastWind 32Error, but I see no method to get a string based on that error. Do I need to use the Win32 function FormatMessage? If so, that defeats the purpose of C# having GetLastWin32Error. Since FormatMessage does so many things besides look up error messages, it tends to be a error codes bit of a burden even in C++. I hate to think of what calling it would be like under C#. ---------- Will Pittenger E-Mail: mailto:wi************@verizon.net All mail filtered by Qurb (www.qurb.com) Nov 15 '05 #1 Post Reply Share this Question 1 Reply P: n/a Mattias Sjögren Will, I see System.Runtime.InteropServices.Marshal.GetLastWind 32Error, but I seeno method to get a string based on that error. Do I need to use the Win32function get win32 error FormatMessage? No, you can do Win32Exception ex = new Win32Exception(); string errMsg = ex.Message; The Win32Exception class internally checks GetLastWin32Error and retrieves the corresponding error message. Mattias -- Mattias Sjögren [MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ Please reply only to the newsgroup. Nov 15 '05 #2 This discussion thread is closed Start new discussion Replies have been disabled for this discussion. Similar topics win32 error Where is the part to set when my mouse pointer move to textbox or label or buton it will display text description ? text/xml reporting service error error moving table to tablespace (8.0 beta win32 ) Find out when text file last saved Can I enter a two-line text description on a button can't run aspnet_setreg on xp i get a "not valid win32 error" How to get text description of an asp error One last try. Error when using #include file= Browse more C# / C Sharp Questions on Bytes Question stats viewed: 8634 replies: 1 date asked: Nov 15 '05 Follow this discussion BYTES.COM © 2016 Formerly "TheScripts.com" from 2005-2008 About Bytes | Advertise on Bytes | Contact Us Sitemap | C# / C Sharp Answers Sitemap | C# / C Sharp Insights Sitemap Follow us to get the Latest Bytes Updates
// // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- /* */ namespace System.ComponentModel { using Microsoft.Win32; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; /// /// The exception that is thrown for a Win32 error code. /// // Code already shipped - safe to place link demand on derived class constructor when base doesn't have it - Suppress message. [HostProtection(SharedState = true)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [Serializable] [SuppressUnmanagedCodeSecurity] public class Win32Exception : ExternalException, ISerializable { /// /// Represents the Win32 error code associated with this exception. This /// field is read-only. /// private readonly int nativeErrorCode; /// /// Initializes a new instance of the class with the last Win32 error /// that occured. /// [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public Win32Exception() : this(Marshal.GetLastWin32Error()) { } /// /// Initializes a new instance of the class with the specified error. /// [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public Win32Exception(int error) : this(error, GetErrorMessage(error)) { } /// /// Initializes a new instance of the class with the specified error and the /// specified detailed description. /// [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public Win32Exception(int error, string message) : base(message) { nativeErrorCode = error; } /// /// Initializes a new instance of the Exception class with a specified error message. /// FxCop CA1032: Multiple constructors are required to correctly implement a custom exception. /// [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public Win32Exception( string message ) : this(Marshal.GetLastWin32Error(), message) { } /// /// Initializes a new instance of the Exception class with a specified error message and a /// reference to the inner exception that is the cause of this exception. /// FxCop CA1032: Multiple constructors are required to correctly implement a custom exception. /// [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] pub