user2578216
user2578216

Reputation: 65

C# ReadProcessMemory error 299

I am trying to read all of a process' memory. I've been using this

        ProcessModule pm = process.MainModule;
        temp = new byte[pm.ModuleMemorySize];
        byte[] d = new byte[temp.Length];
        int read;
        int size = temp.Length;
        MessageBox.Show("Size: " + size);

        if (ReadProcessMemory(process.Handle, pm.BaseAddress, temp, size, out read)) {
            //d = temp;
            fileData = encoder.GetString(temp);
        } else MessageBox.Show("Error: " + Marshal.GetLastWin32Error());

Sometimes this works completely fine, but with other applications it doesn't work at all and returns "Error 299".

I am running my application as x64 and as administrator. It doesn't seem to make a difference what type of process I'm trying to read. Even big ones (26MBs) read just fine. Then I try to read one of my other C# programs and it doesn't work.

EDIT: Is it possible that this only happens when attempting to read C# .exe processes? Why would this be?

Upvotes: 1

Views: 1606

Answers (1)

GuidedHacking
GuidedHacking

Reputation: 3923

If your target is x64, explicitly compile for x64. If your target is x86, explicitly compile for x86. You can find the settings in your project properties.

You must do this because many Windows API structures are different for each architecture, this is because if the structure contains pointers, they are 4 byte on x86 and 8 byte on x64.

Use IntPtr for all addresses/offsets, this will make it use the correct pointer size for the target you're building it for. This way you won't have any issues trying to fit 8 byte values in 4 byte variables.

If you follow this technique you will not have these issues.

Upvotes: 1

Related Questions