esac
esac

Reputation: 24685

How to add a DNS alias programmatically?

I want to create an alias record in Microsoft's DNS server to point AliasA to ComputerA. How can I do this programmatically?

Upvotes: 4

Views: 3052

Answers (2)

esac
esac

Reputation: 24685

I used WMI to do this, found an example on the web, and this is what it looked like.

   private ManagementScope _session = null;

   public ManagementPath CreateCNameRecord(string DnsServerName, string ContainerName, string OwnerName, string PrimaryName)
    {
        _session = new ManagementScope("\\\\" + DnsServerName+ "\\root\\MicrosoftDNS", con);
        _session.Connect();

        ManagementClass zoneObj = new ManagementClass(_session, new ManagementPath("MicrosoftDNS_CNAMEType"), null);
        ManagementBaseObject inParams = zoneObj.GetMethodParameters("CreateInstanceFromPropertyData");
        inParams["DnsServerName"] = ((System.String)(DnsServerName));
        inParams["ContainerName"] = ((System.String)(ContainerName));
        inParams["OwnerName"] = ((System.String)(OwnerName));
        inParams["PrimaryName"] = ((System.String)(PrimaryName));
        ManagementBaseObject outParams = zoneObj.InvokeMethod("CreateInstanceFromPropertyData", inParams, null);

        if ((outParams.Properties["RR"] != null))
        {
            return new ManagementPath(outParams["RR"].ToString());
        }

        return null;
    }

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490118

I don't think .NET has anything to provide access to these (all I can find in a bit of quick searching is references to proprietary libraries, controls, etc.), so you'll probably have to use the Win32 API via P/Invoke (though another possibility would be to do the job via WMI).

You'd start with DnsAcquireContextHandle, then (probably) DnsQuery to get a current record set, modify its contents to add your new alias, DnsReplaceRecordSet to have the DNS server use the new set of records, and finally DnsReleaseContextHandle to shut things down.

Of course, you'll need the right permissions on the server or none of this will work at all.

Upvotes: 0

Related Questions