【转】 用代码获取Oracle服务名清单

/*
        获取Oracle服务名
        1。查询注册表,获取oracle安装根目录
            如:HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\ORACLE_HOME   REG_SZ  E:\ORACLE\ORA92
            得知oracle服务名文件所在地:根目录\network\ADMIN\tnsnames.ora
           
        2。解析该文件,该文件结构如
            # ------------------------------------------------
            PORTAL =
            (DESCRIPTION =
                (ADDRESS_LIST =
                (ADDRESS = (PROTOCOL = TCP)(HOST = 134.104.52.6)(PORT = 1521))
                )
                (CONNECT_DATA =
                (SERVICE_NAME = portal)
                )
            )

        3。解析要点:
            一行一行获取再解析
            跳过以#打头的注释行
            过滤掉空格后,首字符在A~z之间的行就包含了Oracle服务名
            截取该行第一个“=”号左边的字符串,trim处理后就是Oracle服务名了
        */
        public static string[] GetOracleTnsNames()
        {
            try
            {
                // 查询注册表,获取oracle服务文件路径
                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("ORACLE");
                string home = (string)key.GetValue("ORACLE_HOME");
                string file = home + @"\network\ADMIN\tnsnames.ora";

                // 解析文件
                string line;
                ArrayList arr = new ArrayList();
                StreamReader sr = new StreamReader(file);
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line != "")
                    {
                        char c = line[0];
                        if ( c>= 'A' && c<='z')
                            arr.Add(line.Substring(0, line.IndexOf(' ')));
                    }
                }
                sr.Close();

                // 返回字符串数组
                return (string[])arr.ToArray(typeof(string));
            }
            catch (Exception ex)
            {
                return null;
            }
        }

 

 

原文地址:http://www.cnblogs.com/surfsky/archive/2006/08/29/489682.html

 

 

存在的问题:文章中默认获取的注册表中信息是oracle9的,而oracle10和11的注册表结构和oracle9有点区别,不能直接在oracle下获取oracle_home

解决方法:

      // 查询注册表,获取oracle服务文件路径
                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("ORACLE");
                string[] subKeyNames = key.GetSubKeyNames();
                string home = "";
                for (int i = 0; i < subKeyNames.Length; i++)
                {
                    home = (string)key.OpenSubKey(subKeyNames[i]).GetValue("ORACLE_HOME");
                    if (home != null)
                    {
                        break;
                    }
                }
                string file = home + @"\network\ADMIN\tnsnames.ora";

posted on 2010-10-05 10:42  kafony  阅读(293)  评论(0编辑  收藏  举报

导航