Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6010501
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T02:07:31+00:00 2026-05-23T02:07:31+00:00

I have this piece of code that has not been modified but all of

  • 0

I have this piece of code that has not been modified but all of a sudden it has stopped working… I could swear that it used to work but can’t guarantee it. It throws an exception:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

static void Main(string[] args)
{
    ErrorMsg(123);
}

[DllImport("kernel32.dll", EntryPoint = "FormatMessageW", CharSet = CharSet.Auto)]
static extern int FormatMessage(int dwFlags, IntPtr lpSource, long dwMessageId, int dwLanguageId, out IntPtr MsgBuffer, int nSize, IntPtr Arguments);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetThreadLocale();

/// <summary>
/// Gets a Locale specific windows error
/// code specified.
/// </summary>
/// <param name="errorcode">The errorcode.</param>
public static string ErrorMsg(long errorcode)
{
    try
    {
        if (errorcode == 0)
            return "No Error";
        IntPtr pMessageBuffer;
        int dwBufferLength;
        string sMsg;
        int dwFormatFlags;
        //FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS
        dwFormatFlags = 0x00000100 | 0x00000200 | 0x00001000;
        dwBufferLength = FormatMessage(dwFormatFlags, IntPtr.Zero, errorcode, GetThreadLocale(), out pMessageBuffer, 0, IntPtr.Zero);
        if (dwBufferLength == 0)
            return "An Unknown Error Has occured.";
        sMsg = Marshal.PtrToStringUni(pMessageBuffer);
        Marshal.FreeHGlobal(pMessageBuffer);
        return sMsg;
    }
    catch (Exception ex)
    {
        return "An Unknown Error Has occured.";
    }
}

What am I doing wrong here, I can’t seem to find anything? Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T02:07:32+00:00Added an answer on May 23, 2026 at 2:07 am

    Your code worked fine when I tested it on my machine. By the way is there any reason you wouldn’t prefer the following method which is a little shorter and achieves equivalent goal:

    static void Main()
    {
        var ex = new Win32Exception(123);
        Console.WriteLine(ex.Message);
    }
    

    Of course under the covers Win32Exception PInvokes into FormatMessage but at least it’s the .NET framework that should worry about it, not us.


    UPDATE:

    Here’s how the Win32Exception.GetErrorMessage method is implemented in .NET:

    private static string GetErrorMessage(int error)
    {
        string result = "";
        StringBuilder stringBuilder = new StringBuilder(256);
        int num = SafeNativeMethods.FormatMessage(12800, NativeMethods.NullHandleRef, error, 0, stringBuilder, stringBuilder.Capacity + 1, IntPtr.Zero);
        if (num != 0)
        {
            int i;
            for (i = stringBuilder.Length; i > 0; i--)
            {
                char c = stringBuilder[i - 1];
                if (c > ' ' && c != '.')
                {
                    break;
                }
            }
            result = stringBuilder.ToString(0, i);
        }
        else
        {
            result = "Unknown error (0x" + Convert.ToString(error, 16) + ")";
        }
        return result;
    }
    

    where FormatMessage is declared like this:

    [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this piece of code that does not work: public CartaoCidadao() { InitializeComponent();
I have this piece of code that is giving me trouble. I know all
I have this piece of code that works fine in subsonic 2.2, I migrated
I have this small piece of code that basically takes a list and runs
Assume that I have this piece of code: @interface Foo : NSObject { Bar
I have a program I wrote in Windows with this piece of code that
I have this program that should execute a piece of code base on the
I have a piece of code that look similar to this: <xsl:choose> <xsl:when test=some_test>
I have a piece of code that the ARC converter turned into this... //
I have a DSL - like piece of Ruby code that looks like this:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.