Arithmetic operation resulted in an overflow c#

H20rider picture H20rider · Apr 7, 2016 · Viewed 7.4k times · Source

I am getting the following error when unlocking a file

Arithmetic operation resulted in an overflow

System.IntPtr.ToInt32

I suspect it is the following line to pBuffer.ToInt32() :

IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3)));

I am unable to reproduce the error myself and the error is not displaying the correct line number. I am looking for a way to reproduce this or any feedback on the possible cause. Thanks

public void Close()
{
        const int MAX_PREFERRED_LENGTH = -1;
        int readEntries;
        int totalEntries;
        IntPtr pBuffer = IntPtr.Zero;
        FILE_INFO_3 fi3 = new FILE_INFO_3();
        int iStatus = NetFileEnum(this.HostName, this.HostPathToShare + this.FileNameFromShare, null, 3, ref pBuffer, MAX_PREFERRED_LENGTH, out readEntries, out totalEntries, pBuffer);
        if (iStatus == 0)
        {
            for (int i = 0; i < readEntries; i++)
            {
                IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3)));
                fi3 = (FILE_INFO_3)Marshal.PtrToStructure(iPtr, typeof(FILE_INFO_3));
                NetFileClose(this.HostName, fi3.fi3_id);
            }
        }
        NetApiBufferFree(pBuffer);
}

[DllImport("netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
static extern int NetFileClose(
    string servername,
    int id);

[DllImport("Netapi32.dll", SetLastError=true)]
static extern int NetApiBufferFree(IntPtr Buffer);

[DllImport("netapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern int NetFileEnum(
     string servername,
     string basepath,
     string username,
     int level,
     ref IntPtr bufptr,
     int prefmaxlen,
     out int entriesread,
     out int totalentries,
     IntPtr resume_handle
);

Update

I added the win32 apis code.

The below answers look correct and the machine is 64 bit. But I am unable to reproduce it on the dev server despite the dev environment being 64 bit. Any ideas to reproduce the error?

Answer

CodeCaster picture CodeCaster · Apr 7, 2016

The error is caused by your code running in a 64 bit context and returning a pointer address that lies outside the range addressable with 32 bits, so .ToInt32() throws.

Call Environment.Is64BitProcess to detect whether your process is running in 32 or 64 bit, and convert the address accordingly:

long pointerAddress;

if (Environment.Is64BitProcess)
{
    pointerAddress = pBuffer.ToInt64(); 
}
else
{
    pointerAddress = pBuffer.ToInt32(); 
}

var fileInfoPointer = new IntPtr(pointerAddress + (i * Marshal.SizeOf(fi3)));