/*
本组件是为了获得本地Oracle服务名所写的。
本组件使用 .net 2005 编写。所以使用该组件必须安装framwork 2.0
写的很简漏 如有bug请联系我一起学习 (xxj_jing@126.com)
---
以下是代码部分,供参考!
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Collections;
using System.Windows.Forms;
namespace OracleServiceControl
{
/// <summary>
/// 2008-06-25 xxj_jing@126.com
/// </summary>
public partial class OracleServiceComboBox : System.Windows.Forms.ComboBox
{
public OracleServiceComboBox()
{
InitializeComponent();
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.InitCmb();
}
public OracleServiceComboBox(IContainer container)
{
container.Add(this);
InitializeComponent();
}
/// <summary>
/// 为控件赋值
/// </summary>
private void InitCmb()
{
string[] arr = this.GetAllServices();
if (arr == null)
{
//MessageBox.Show("Error");
return;
}
foreach (string str in arr)
{
this.Items.Add(str);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.InitCmb();
}
private string m_error = string.Empty;
/// <summary>
/// 获取oracle安装路径
/// </summary>
/// <param name="setupKey">要读取的注册表键</param>
/// <returns>返回Oracle安装路径</returns>
private string ReadHomeOracleDirectory(string setupKey)
{
RegistryKey reg;
try
{
reg = Registry.LocalMachine.OpenSubKey("Software\\ORACLE", false);
foreach (string name in reg.GetValueNames())
{
if (name == setupKey)
{
return reg.GetValue(name).ToString();
}
}
return null;
}
catch (Exception ex)
{
this.m_error = ex.Message;
return null;
}
}
/// <summary>
/// 读取oracle 本地服务名存储文件
/// </summary>
/// <returns>返回一个包含所有服务名的数组</returns>
private string[] GetAllServices()
{
ArrayList arr = new ArrayList();
string path = ReadHomeOracleDirectory("ORACLE_HOME");
if (path == null)
{
MessageBox.Show(this.m_error);
return null;
}
string pathName = path + @"\network\admin\tnsnames.ora";
if (!System.IO.File.Exists(pathName))
{
this.Text = pathName + " 文件不存在!";
return null;
}
try
{
StreamReader sr = new StreamReader(pathName);
string str = string.Empty;
while ((str = sr.ReadLine()) != null)
{
str = str.Trim();
if (str != "")
{
if (str[0] >= 'A' && str[0] <= 'z')
{
arr.Add(str.Substring(0, str.IndexOf("=")).Trim());
}
}
}
sr.Dispose();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
this.m_error = ex.Message;
}
return (string[])arr.ToArray(typeof(string));
}
}
}