How to get around DnsRecordListFree error in .NET Framework 4.0?

Posted by Greg Finzer on Stack Overflow See other posts from Stack Overflow or by Greg Finzer
Published on 2010-05-25T16:44:50Z Indexed on 2010/05/25 16:51 UTC
Read the original article Hit count: 259

Filed under:

I am doing an MxRecordLookup. I am getting an error when calling the DnsRecordListFree in the .NET Framework 4.0. I am using Windows 7. How do I get around it? Here is the error:

System.MethodAccessException: Attempt by security transparent method to call native code through method.

Here is my code:

    [DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
    private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved);

    [DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType);

    public List<string> GetMXRecords(string domain)
    {
        List<string> records = new List<string>();
        IntPtr ptr1 = IntPtr.Zero;
        IntPtr ptr2 = IntPtr.Zero;
        MXRecord recMx;

        try
        {

            int result = DnsQuery(ref domain, QueryTypes.DNS_TYPE_MX, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0);
            if (result != 0)
            {
                if (result == 9003)
                {
                    //No Record Exists
                }
                else
                {
                    //Some other error
                }
            }

            for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recMx.pNext)
            {
                recMx = (MXRecord)Marshal.PtrToStructure(ptr2, typeof(MXRecord));
                if (recMx.wType == 15)
                {
                    records.Add(Marshal.PtrToStringAuto(recMx.pNameExchange));
                }
            }
        }
        finally
        {
            DnsRecordListFree(ptr1, 0);
        }

        return records;
    }

© Stack Overflow or respective owner

Related posts about c#4.0