欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#利用WMI操作DNS服务器(可远程操作,需要相应权限)

程序员文章站 2022-06-03 11:04:15
using system; using system.collections.generic; using system.text; usin...
using system;
using system.collections.generic;
using system.text;
using system.data;

namespace yaosansi
{
    class test
    {
        static void main()
        {
            mydnstest();
        }

    /// <summary>
    /// mydnstest功能测试
  /// c#利用wmi操作dns服务器(可远程操作,需要相应权限)
    /// author:yaosansi 
    /// create date:2005-09-07
    /// modify date:2006-10-25
    /// site:http://www.yaosansi.com/
    /// e-mail:yaosansi at 126 dot com
    /// http://www.yaosansi.com/blog/article.asp?id=935
    /// http://yaosansi.cnblogs.com/archive/2006/11/04/dnsserviceincsharpwithwmi.html
    /// 注意:此版本为windows2003 dns服务器专用.不适合其它版本操作系统.
    /// </summary>
        static void mydnstest()
        {
            yaosansi.net.mydns dns = new yaosansi.net.mydns();
            //===========================================
            //不对以下三个属性赋值默认dns服务器为本机.
            dns.servername = "202.96.64.68";
            dns.username = "administrator";
            dns.password = "123456789";
            //===========================================
            //dns.createzone("yaosansi.com");
            //dns.delzone("yaosansi.com");
            //dns.createatype("yaosansi.com", "www", "2.2.2.2", "3600");
            //dns.modifyatype("yaosansi.com","www","127.21.0.1","800");
            //dns.delatype("yaosansi.com", "mail");
            //dns.createmxtype("mail", "yaosansi.com", "5.5.5.5", "20", "3600");
            //dns.modifymxtype("mail", "yaosansi.com", "36000", "218.1.1.1", "26");
            //dns.delmxtype("mail", "yaosansi.com");
            //dns.createcnametype("mpq2", "yaosansi.com", "www.yaosansi.com", "3900");
            //dns.modifycnametype("mpq2", "abc.com", "30520", "www.yaosansi.com.");
            //dns.delcnametype("mpq", "yaosansi.com");

            //datatable table = dns.listexistsmxtype("yaosansi.com");
            datatable table = dns.listexistsatype("yaosansi.com");
            //datatable table = dns.listexistscnametype("yaosansi.com");
            yaosansi.data.datahelp.printtable(table);

            if (!string.isnullorempty(dns.errmessage))
            {
                console.writeline("--------------------------------------------------");
                console.writeline("返回信息:" + dns.errmessage);
                console.writeline("--------------------------------------------------");
            }
            console.writeline("");
            console.writeline("===end===");
            console.readline();
        }
    }
}





using system;
using system.management;
using system.data;

namespace yaosansi.net
{
    /// <summary>
    /// c#利用wmi操作dns服务器(可远程操作,需要相应权限)
    /// author:yaosansi 
    /// create date:2005-09-07
    /// modify date:2006-10-25
    /// site:http://www.yaosansi.com/
    /// e-mail:yaosansi at 126 dot com
    /// http://www.yaosansi.com/blog/article.asp?id=935
    /// http://yaosansi.cnblogs.com/archive/2006/11/04/dnsserviceincsharpwithwmi.html
    /// 注意:此版本为windows2003 dns服务器专用.不适合其它版本操作系统.
    /// </summary>
    public class mydns
    {
        //要连接的dns服务器
        private string sserverpath;
        //用户名
        private string username = null;
        //密码
        private string password = null;
        //服务器名称或ip地址
        private string dnsname = null;
        //表示管理操作的范围.这里是用来执行dns的命名空间
        private managementscope dns;
        //用于返回检索的managementobject集合
        private system.management.managementobjectcollection q;
        //
        private managementclass dnsclass;
        //
        private managementbaseobject mi;

        /// <summary>
        /// 返回的操作信息.
        /// </summary>
        private string errmessage=null;

        /// <summary>
        /// 获取错误信息.
        /// </summary>
        public string errmessage
        {
            get
            {
                return errmessage;
            }
        }
        /// <summary>
        /// 设置dns服务器名称或ip地址
        /// </summary>
        public string servername
        {
            set
            {
                this.sserverpath = string.format(@"\\{0}\root\microsoftdns", value);
                this.dnsname = value;
            }
        }

        /// <summary>
        /// 设置连接服务器的用户名(指定服务器ip,用户和密码后将自动连接远程服务器,本机不需要指定)
        /// </summary>
        public string username
        {
            set
            {
                this.username = value;
            }
        }

        /// <summary>
        /// 设置连接服务器的密码(指定服务器ip,用户和密码后将自动连接远程服务器,本机不需要指定)
        /// </summary>
        public string password
        {
            set
            {
                this.password = value;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public mydns()
        {
            sserverpath = @"\\localhost\root\microsoftdns";
            dnsname = "localhost";
        }



        /// <summary>
        /// 建立对象.连接
        /// </summary>
        /// <param name="dnstype">dns类型 microsoftdns_zone等</param>
        private void create(string dnstype)
        {
            if (!string.isnullorempty(username) && !string.isnullorempty(password))
            {
                system.management.connectionoptions conn = new connectionoptions();
                conn.username = username; //用户名
                conn.password = password; //口令
                dns = new managementscope(sserverpath,conn);
            }
            else
            {
                dns = new managementscope(sserverpath);
            }
            if (!dns.isconnected)
            {
                dns.connect();
            }
            managementpath path = new managementpath(dnstype);
            this.dnsclass = new managementclass(dns, path, null);
        }

        /// <summary>
        /// 查询dns并建立对象
        /// </summary>
        /// <param name="query">wql查询语句</param>
        ///  <param name="dnstype">dns类型 microsoftdns_zone等</param>
        /// <returns></returns>
        public managementobjectcollection querydns(string query, string dnstype)
        {
            this.create(dnstype);
            system.management.managementobjectsearcher qs = new managementobjectsearcher(dns, new objectquery(query));
            qs.scope = dns;
            return qs.get();
        }

        /// <summary>
        /// 仅查询dns
        /// </summary>
        /// <param name="query">wql查询语句</param>
        /// <returns></returns>
        public managementobjectcollection querydns(string query)
        {
            if (!string.isnullorempty(username) && !string.isnullorempty(password))
            {
                system.management.connectionoptions conn = new connectionoptions();
                conn.username = username; //用户名
                conn.password = password; //口令
                dns = new managementscope(sserverpath, conn);
            }
            else
            {
                dns = new managementscope(sserverpath);
            }
            if (!dns.isconnected)
            {
                dns.connect();
            }
            system.management.managementobjectsearcher qs = new managementobjectsearcher(dns, new objectquery(query));
            qs.scope = dns;
            return qs.get();
        }


        /// <summary>
        /// 判断区域是否存在
        /// </summary>
        /// <param name="domain">区域名称</param>
        /// <returns></returns>
        public bool isexistszone(string domain)
        {

            try
            {
                q = querydns("select * from microsoftdns_zone where containername='" + domain + "'");
                foreach (managementobject omanobject in q)
                {
                    //console.writeline(omanobject["containername"].tostring());
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }




        /// <summary>
        /// 创建一个新的区域,仅区域名称
        /// </summary>
        /// <param name="domain">区域的名称</param>
        public bool createzone(string domain)
        {
            try
            {
                this.create("microsoftdns_zone");
                //如果区域已经存在
                if (isexistszone(domain))
                {
                    errmessage = "域:"+domain+"已经存在.";
                    return false;
                }
                //建立新的区域
                this.mi = dnsclass.getmethodparameters("createzone");
                this.mi["zonename"] = domain;
                this.mi["zonetype"] = 0;

                managementbaseobject outparams = this.dnsclass.invokemethod("createzone", mi, null);
                errmessage = "域:"+domain+"创建成功.";
                return true;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }


        /// <summary>
        /// 创建一个区域,包括其它参数
        /// </summary>
        /// <param name="domain">要创建的区域名称</param>
        /// <param name="zonetype">type of zone. valid values are the following:0 primary zone. 1 secondary zone.  2 stub zone. 3 zone forwarder. </param>
        /// <param name="datafilename">[in, optional] name of the data file associated with the zone</param>
        /// <param name="ipaddr">[in, optional] ip address of the mater dns server for the zone. </param>
        /// <param name="adminemailname">[in, optional] email address of the administrator responsible for the zone</param>
        /// <returns></returns>
        public bool createzone(string domain, uint zonetype, string datafilename, string[] ipaddr, string adminemailname)
        {
            try
            {
                this.create("microsoftdns_zone");
                //如果区域已经存在
                if (isexistszone(domain))
                {
                    errmessage = "域:" + domain + "已经存在.";
                    return false;
                }
                //建立新的区域
                mi = dnsclass.getmethodparameters("createzone");
                mi["zonename"] = domain;
                mi["zonetype"] = zonetype;
                mi["datafilename"] = datafilename;
                mi["ipaddr"] = ipaddr;
                mi["adminemailname"] = adminemailname;
                managementbaseobject outparams = this.dnsclass.invokemethod("createzone", mi, null);
                errmessage = "域:" + domain + "创建成功.";
                return true;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }


        /// <summary>
        /// 修改区域
        /// </summary>
        /// <param name="domain">要修改的区域名称</param>
        /// <param name="zonetype">type of zone. valid values are the following:0 primary zone. 1 secondary zone.  2 stub zone. 3 zone forwarder. </param>
        /// <param name="datafilename">[in, optional] name of the data file associated with the zone</param>
        /// <param name="ipaddr">[in, optional] ip address of the mater dns server for the zone. </param>
        /// <param name="adminemailname">[in, optional] email address of the administrator responsible for the zone</param>
        /// <returns></returns>
        public bool changezonetype(string domain, uint zonetype, string datafilename, string[] ipaddr, string adminemailname)
        {
            try
            {
                q = querydns("select * from microsoftdns_zone where containername='" + domain + "'", "microsoftdns_zone");

                foreach (managementobject omanobject in q)
                {
                    mi = omanobject.getmethodparameters("changezonetype");
                    mi["zonetype"] = zonetype;
                    mi["datafilename"] = datafilename;
                    mi["ipaddr"] = ipaddr;
                    mi["adminemailname"] = adminemailname;
                    omanobject.invokemethod("changezonetype", mi, null);
                    errmessage = "域:" + domain + "修改成功.";
                    return true;
                }
                errmessage = "未找到域:"+domain;
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }

        /// <summary>
        /// 删除区域
        /// </summary>
        /// <param name="domain">要册除的区域的名称</param>
        /// <returns></returns>
        public bool delzone(string domain)
        {
            try
            {
                q = querydns("select * from microsoftdns_zone where containername='" + domain + "'", "microsoftdns_zone");
                foreach (managementobject omanobject in q)
                {
                    omanobject.delete();
                    errmessage = "域:" + domain + "删除成功.";
                    return true;
                }
                errmessage = "未找到域:" + domain;
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }

        /// <summary>
        /// 判断在某microsoftdns_atype是否在指定的域中存在
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="ownername"></param>
        /// <returns></returns>
        public bool isexistsatype(string domain, string ownername)
        {
            try
            {
                q = querydns("select * from microsoftdns_atype where ownername='" + ownername + "' and containername='" + domain + "'");
                foreach (managementobject omanobject in q)
                {
                    //console.writeline(omanobject["ownername"].tostring());
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }


        /// <summary>
        /// 创建microsoftdns_atype 
        /// </summary>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="ttl">time, in seconds, that the rr can be cached by a dns resolver</param>
        /// <param name="ipaddress">string representing the ipv4 address of the host</param>
        /// <returns></returns>
        public bool createatype(string containername, string hostname, string ipaddress,string ttl)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }
                this.create("microsoftdns_atype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,创建失败", containername);
                    errmessage = string.format("区域:{0}不存在,创建失败", containername);
                    return false;
                }
                if (isexistsatype(containername, ownername))
                {
                    console.writeline("{0}中已存在{1},创建失败", containername, ownername);
                    errmessage = string.format("{0}中已存在{1},创建失败", containername, ownername);
                    return false;
                }
                mi = dnsclass.getmethodparameters("createinstancefrompropertydata");
                mi["dnsservername"] = "localhost";
                mi["containername"] = containername;
                mi["ownername"] = ownername;
                mi["ipaddress"] = ipaddress;
                if (string.isnullorempty(ttl))
                {
                    ttl = "3600";
                }
                mi["ttl"] =ttl;
                dnsclass.invokemethod("createinstancefrompropertydata", mi, null);
                errmessage = "a记录:" + ownername + "创建成功.";
                return true;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }


        /// <summary>
        /// 创建microsoftdns_atype 
        /// </summary>
        /// <param name="dnsservername">fqdn or ip address of the dns server that contains this rr</param>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="recordclass">class of the rr. default value is 1. the following values are valid.1 in (internet) 2 cs (csnet)  3 ch (chaos) 4 hs (hesiod) </param>
        /// <param name="ttl">time, in seconds, that the rr can be cached by a dns resolver</param>
        /// <param name="ipaddress">string representing the ipv4 address of the host</param>
        /// <returns></returns>
        public bool createatype(string dnsservername, string containername, string hostname, uint recordclass, uint ttl, string ipaddress)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }
                this.create("microsoftdns_atype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,创建失败", containername);
                    errmessage = string.format("区域:{0}不存在,创建失败", containername);
                    return false;
                }
                if (isexistsatype(containername, ownername))
                {
                    console.writeline("{0}中已存在{1},创建失败", containername, ownername);
                    errmessage=string.format("{0}中已存在{1},创建失败", containername, ownername);
                    return false;
                }
                mi = dnsclass.getmethodparameters("createinstancefrompropertydata");
                mi["dnsservername"] = dnsservername;
                mi["containername"] = containername;
                mi["ownername"] = ownername;
                mi["recordclass"] = recordclass;
                mi["ttl"] = ttl;
                mi["ipaddress"] = ipaddress;
                dnsclass.invokemethod("createinstancefrompropertydata", mi, null);
                errmessage = "a记录:" + ownername + "创建成功.";
                return true;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }


        /// <summary>
        /// 修改microsoftdns_atype 
        /// </summary>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="ttl">time, in seconds, that the rr can be cached by a dns resolver</param>
        /// <param name="ipaddress"></param>
        /// <returns></returns>
        public bool modifyatype(string containername, string hostname, string ipaddress,string ttl)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,修改失败", containername);
                    errmessage = string.format("区域:{0}不存在,修改失败", containername);
                    return false;
                }
                if (!isexistsatype(containername, ownername))
                {
                    console.writeline("{0}中不存在{1},修改失败", containername, ownername);
                    errmessage = string.format("{0}中不存在{1},修改失败", containername, ownername);
                    return false;
                }


                q = querydns("select * from microsoftdns_atype where containername='" + containername + "' and ownername='" + ownername + "'", "microsoftdns_atype");

                foreach (managementobject omanobject in q)
                {
                    //foreach (propertydata p in omanobject.properties)
                    //{
                    //    try
                    //    { console.writeline(p.name+"="+omanobject[p.name]); }
                    //    catch
                    //    { }
                    //}
                    if (omanobject["ipaddress"].tostring() == ipaddress)
                    {
                        errmessage = "a记录:" + ownername + "修改失败,必须修改ip地址.";
                        return false;
                    }

                    mi = omanobject.getmethodparameters("modify");
                    mi["ipaddress"] = ipaddress;
                    mi["ttl"] = ttl;
                    omanobject.invokemethod("modify", mi, null);
                    errmessage = "a记录:" + ownername + "修改成功.";
                    return true;
                }
                errmessage = string.format("{0}中不存在{1},修改失败", containername, ownername);
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }





        /// <summary>
        /// 删除microsoftdns_atype
        /// </summary>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <returns></returns>
        public bool delatype(string containername, string hostname)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,删除失败", containername);
                    errmessage = string.format("区域:{0}不存在,删除失败", containername);
                    return false;
                }
                if (!isexistsatype(containername, ownername))
                {
                    console.writeline("{0}中不存在{1},删除失败", containername, ownername);
                    errmessage = string.format("{0}中不存在{1},删除失败", containername, ownername);
                    return false;
                }

                q = querydns("select * from microsoftdns_atype where containername='" + containername + "' and ownername='" + ownername + "'", "microsoftdns_atype");

                foreach (managementobject omanobject in q)
                {
                    omanobject.delete();
                    errmessage = "a记录:" + ownername + "删除成功.";
                    return true;
                }
                errmessage = string.format("{0}中不存在{1},删除失败", containername, ownername);
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }


        /// <summary>
        /// 列出某域名下的所有a记录.
        /// </summary>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <returns></returns>
        public datatable listexistsatype(string containername)
        {
            yaosansi.io.log log = new yaosansi.io.log();
            log.wirtelogtime();
            log.wirtelog(containername);

            datatable table = new datatable("microsoftdns_atype" + containername);
            table.columns.add("主机名 (a)");
            table.columns.add("ip 地址");
            table.columns.add("ttl");
            try
            {
                q = querydns("select * from microsoftdns_atype where containername='" + containername + "'");

                foreach (managementobject omanobject in q)
                {
                    try
                    {
                        datarow row = table.newrow();
                        row["主机名 (a)"] = omanobject["ownername"];
                        row["ip 地址"] = omanobject["ipaddress"];
                        row["ttl"] = omanobject["ttl"];
                        table.rows.add(row);
                    }
                    catch (exception e) { log.wirtelog(e.tostring()); }
                }
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                log.wirtelog(e.tostring());
            }
            yaosansi.data.datahelp.printtablelog(table);
            return table;
        }



        /// <summary>
        /// 列出某域名下的所有mx记录.
        /// </summary>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <returns></returns>
        public datatable listexistsmxtype(string containername)
        {
            datatable table = new datatable("microsoftdns_mxtype" + containername);
            table.columns.add("邮件交换记录 (mx)");
            table.columns.add("目标主机");
            table.columns.add("优先级");
            table.columns.add("ttl");
            try
            {
                q = querydns("select * from microsoftdns_mxtype where containername='" + containername + "'");

                foreach (managementobject omanobject in q)
                {
                    try
                    {
                        datarow row = table.newrow();
                        row["目标主机"] = omanobject["mailexchange"];
                        row["邮件交换记录 (mx)"] = omanobject["ownername"];
                        row["优先级"] = omanobject["preference"];
                        row["ttl"] = omanobject["ttl"];
                        table.rows.add(row);
                    }
                    catch { }
                }
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
            }
            return table;
        }


        /// <summary>
        /// 列出某域名下的所有别名.
        /// </summary>
        /// <param name="containername">name of the container for the zone, cache, or roothints instance which contains this rr</param>
        /// <returns></returns>
        public datatable listexistscnametype(string containername)
        {
            datatable table = new datatable("microsoftdns_cnametype" + containername);
            table.columns.add("别名 (cname)");
            table.columns.add("别名主机");
            table.columns.add("ttl");
            try
            {
                q = querydns("select * from microsoftdns_cnametype where containername='" + containername + "'");
                foreach (managementobject omanobject in q)
                {
                    try
                    {
                        datarow row = table.newrow();
                        row["别名 (cname)"] = omanobject["ownername"];
                        row["别名主机"] = omanobject["primaryname"];
                        row["ttl"] = omanobject["ttl"];
                        table.rows.add(row);
                    }
                    catch { }
                }
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
            }
            return table;
        }


        /// <summary>
        /// 判断在某microsoftdns_mxtype是否在指定的域中存在
        /// </summary>
        /// <param name="containername">主域名 主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <param name="ownername">owner name for the rr. </param>
        /// <returns></returns>
        public bool isexistsmxtype(string containername, string ownername)
        {           
            try
            {

                q = querydns("select * from microsoftdns_mxtype where containername='" + containername + "' and ownername='" + ownername + "'");

                foreach (managementobject omanobject in q)
                {
                  //  console.writeline(omanobject["mailexchange"].tostring());
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }

        /// <summary>
        /// 创建microsoftdns_mxtype记录(邮件交换记录)
        /// </summary>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="containername">主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <param name="mailexchange">目标主机 fqdn specifying a host willing to act as a mail exchange for the owner name</param>
        /// <param name="preference">优先级 preference given to this rr among others at the same owner. lower values are preferred</param>
        /// <param name="ttl">time, in seconds, that the rr can be cached by a dns resolver</param>
        /// <returns></returns>
        public bool createmxtype(string hostname, string containername,string mailexchange, string preference, string ttl)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                this.create("microsoftdns_mxtype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,创建失败", containername);
                    errmessage = string.format("区域:{0}不存在,创建失败", containername);
                    return false;
                }
                if (isexistsmxtype(containername,ownername))
                {
                    console.writeline("{0}中已存在{1},创建失败", containername,ownername );
                    errmessage = string.format("{0}中已存在{1},创建失败", containername, ownername);
                    return false;
                }

                mi = dnsclass.getmethodparameters("createinstancefrompropertydata");

                mi["dnsservername"] = "localhost";
                mi["containername"] = containername;
                // mi["recordclass"] = 1;  //default value is 1.  //1 in (internet)  //2 cs (csnet)   //3 ch (chaos)   //4 hs (hesiod) 
                mi["mailexchange"] = mailexchange;
                mi["ownername"] = ownername;
                mi["preference"] = preference;

                if (string.isnullorempty(ttl))
                {
                    ttl = "3600";
                }
                mi["ttl"] = ttl;
                dnsclass.invokemethod("createinstancefrompropertydata", mi, null);
                errmessage = "mx记录:" + ownername + "创建成功.";
                return true;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }

        /// <summary>
        /// 修改microsoftdns_mxtype记录(修改邮件交换记录)
        /// </summary>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="containername">主域名 主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <param name="ttl">[in, optional] time, in seconds, that the rr can be cached by a dns resolver. </param>
        /// <param name="mailexchange">[in, optional] fqdn specifying a host willing to act as a mail exchange for the owner name. </param>
        /// <param name="preference">邮件优先级 [in, optional] preference given to this rr among others at the same owner. lower values are preferred. </param>
        /// <returns></returns>
        public bool modifymxtype(string hostname, string containername, string ttl, string mailexchange,string preference)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                this.create("microsoftdns_mxtype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,修改失败", containername);
                    errmessage = string.format("区域:{0}不存在,修改失败", containername);
                    return false;
                }
                if (!isexistsmxtype(containername, ownername))
                {
                    console.writeline("{0}中不存在{1},修改失败", containername, ownername);
                    errmessage = string.format("{0}中不存在{1},修改失败", containername, ownername);
                    return false;
                }
                q = querydns("select * from microsoftdns_mxtype where containername='" + containername + "' and ownername='" + ownername + "'"); 
                foreach (managementobject omanobject in q)
                {
                    mi = omanobject.getmethodparameters("modify");
                    if (string.isnullorempty(ttl))
                    {
                        ttl = "3600";
                    }

                    if (clearenddot(omanobject["mailexchange"].tostring()) == clearenddot(mailexchange) && omanobject["preference"].tostring() == preference)
                    {
                        errmessage = "mx记录:" + ownername + "修改失败,必须修改目标主机或邮件优先级.";
                        return false;
                    }

                    mi["ttl"] = ttl;
                    mi["mailexchange"] = mailexchange;
                    mi["preference"] = preference;
                    omanobject.invokemethod("modify", mi, null);
                    errmessage = "mx记录:" + ownername + "修改成功.";
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }



        /// <summary>
        /// 删除microsoftdns_mxtype
        /// </summary>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="containername">主域名 主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <returns></returns>
        public bool delmxtype(string hostname, string containername)
        {
            try
            { 
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                this.create("microsoftdns_mxtype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,删除失败", containername);
                    errmessage = string.format("区域:{0}不存在,删除失败", containername);
                    return false;
                }
                if (!isexistsmxtype(containername, ownername))
                {
                    console.writeline("{0}中不存在{1},删除失败", containername, ownername);
                    errmessage = string.format("{0}中不存在{1},删除失败", containername, ownername);
                    return false;
                }
                q = querydns("select * from microsoftdns_mxtype where containername='" + containername + "' and ownername='" + ownername + "'");

                foreach (managementobject omanobject in q)
                {
                    omanobject.delete();
                    errmessage = "mx记录:" + ownername + "删除成功.";
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }


        /// <summary>
        /// 判断在某microsoftdns_cnametype是否在指定的域中存在
        /// </summary>
        /// <param name="containername">主域名 主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <param name="ownername">owner name for the rr. </param>
        /// <returns></returns>
        public bool isexistscnametype(string containername, string ownername)
        {
            try
            {

                q = querydns("select * from microsoftdns_cnametype where containername='" + containername + "' and ownername='" + ownername + "'");

                foreach (managementobject omanobject in q)
                {
                    //  console.writeline(omanobject["mailexchange"].tostring());
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }

        /// <summary>
        /// 创建microsoftdns_cnametype记录(别名)
        /// </summary>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="containername">主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <param name="primaryname">in] primary name of the cname rr</param>
        /// <param name="ttl">time, in seconds, that the rr can be cached by a dns resolver</param>
        /// <returns></returns>
        public bool createcnametype(string hostname, string containername, string primaryname,  string ttl)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                this.create("microsoftdns_cnametype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,创建失败", containername);
                    errmessage = string.format("区域:{0}不存在,创建失败", containername);
                    return false;
                }
                if (isexistscnametype(containername, ownername))
                {
                    console.writeline("{0}中已存在{1},创建失败", containername, ownername);
                    errmessage = string.format("{0}中已存在{1},创建失败", containername, ownername);
                    return false;
                }

                mi = dnsclass.getmethodparameters("createinstancefrompropertydata");

                mi["dnsservername"] = "localhost";
                mi["containername"] = containername;
                // mi["recordclass"] = 1;  //default value is 1.  //1 in (internet)  //2 cs (csnet)   //3 ch (chaos)   //4 hs (hesiod) 
                mi["primaryname"] = primaryname;
                mi["ownername"] = ownername;

                if (string.isnullorempty(ttl))
                {
                    ttl = "3600";
                }
                mi["ttl"] = ttl;
                dnsclass.invokemethod("createinstancefrompropertydata", mi, null);
                errmessage = "cname:" + ownername + "创建成功.";
                return true;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }

        }

        /// <summary>
        /// 修改microsoftdns_cnametype记录(别名)
        /// </summary>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="containername">主域名 主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <param name="ttl">[in, optional] time, in seconds, that the rr can be cached by a dns resolver. </param>
        /// <param name="primaryname">in] primary name of the cname rr</param>
        /// <returns></returns>
        public bool modifycnametype(string hostname, string containername, string ttl, string primaryname)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                this.create("microsoftdns_cnametype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,修改失败", containername);
                    errmessage = string.format("区域:{0}不存在,修改失败", containername);
                    return false;
                }
                if (!isexistscnametype(containername, ownername))
                {
                    console.writeline("{0}中不存在{1},修改失败", containername, ownername);
                    errmessage = string.format("{0}中不存在{1},修改失败", containername, ownername);
                    return false;
                }
                q = querydns("select * from microsoftdns_cnametype where containername='" + containername + "' and ownername='" + ownername + "'");
                foreach (managementobject omanobject in q)
                {
                    if (clearenddot(omanobject["primaryname"].tostring()) == clearenddot(primaryname))
                    {
                        errmessage = "cname记录:" + ownername + "修改失败,必须修改别名主机.";
                        return false;
                    }


                    mi = omanobject.getmethodparameters("modify");
                    if (string.isnullorempty(ttl))
                    {
                        ttl = "3600";
                    }
                    mi["ttl"] = ttl;
                    mi["primaryname"] = primaryname;
                    omanobject.invokemethod("modify", mi, null);
                    errmessage = "cname:" + ownername + "修改成功.";
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }



        /// <summary>
        /// 删除microsoftdns_cnametype
        /// </summary>
        /// <param name="hostname">主机名 [如果为空或null,主机名将与域名保持一致.]</param>
        /// <param name="containername">主域名 主域 name of the container for the zone, cache, or roothints instance that contains this rr.</param>
        /// <returns></returns>
        public bool delcnametype(string hostname, string containername)
        {
            try
            {
                string ownername = null;
                if (string.isnullorempty(hostname))
                {
                    ownername = containername;
                }
                else
                {
                    ownername = hostname + "." + containername;
                }

                this.create("microsoftdns_cnametype");
                //如果区域不存在
                if (!isexistszone(containername))
                {
                    console.writeline("区域:{0}不存在,删除失败", containername);
                    errmessage = string.format("区域:{0}不存在,删除失败", containername);
                    return false;
                }
                if (!isexistscnametype(containername, ownername))
                {
                    console.writeline("{0}中不存在{1},删除失败", containername, ownername);
                    errmessage = string.format("{0}中不存在{1},删除失败", containername, ownername);
                    return false;
                }
                q = querydns("select * from microsoftdns_cnametype where containername='" + containername + "' and ownername='" + ownername + "'");

                foreach (managementobject omanobject in q)
                {
                    omanobject.delete();
                    errmessage = "cname:" + ownername + "删除成功.";
                    return true;
                }
                return false;
            }
            catch (exception e)
            {
                errmessage = e.message;
                console.writeline(e.tostring());
                return false;
            }
        }


        /// <summary>
        /// 去除以.结尾的字符串的.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string clearenddot(string str)
        {
            string returnstr = str;
            if (!string.isnullorempty(str))
            {
                int l = str.lastindexof(".");
                if (l != -1 && l == str.length - 1)
                {
                    returnstr = str.substring(0, str.length - 1);
                }
            }
            return returnstr;
        }

    }
}