4

如何使用 Visual C#(Visual Studio 2008 Express 版)解析 tnsnames.ora 文件以获取 tnsnames ?例如,我的 tnsnames.ora 文件包含

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = shaman)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )
BILL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.10.58)(PORT = 1522))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

如何解析该文件以获取 TNSNAMES(即 ORCL、BILL 等)。如果这个问题听起来太明显,请原谅我,我正在学习并尝试使用 C#

4

4 回答 4

4

首先,您需要该文件的语法规则

这可能有一个 hack,但我个人会使用完整的解析器,比如ANTLR结合正确的语法(可以在此处找到ANTLR 语法的完整列表)。

于 2009-08-07T06:10:06.967 回答
1
public List<string> ReadTextFile(string FP)
{

    string inputString;
    List<string> List = new List<string>();

    try
    {
        StreamReader streamReader = File.OpenText(FP.Trim()); // FP is the filepath of TNS file

        inputString = streamReader.ReadToEnd();
        string[] temp = inputString.Split(new string[] {Environment.NewLine},StringSplitOptions.None);

        for (int i = 0; i < temp.Length ;i++ )
        {
            if (temp[i].Trim(' ', '(').Contains("DESCRIPTION"))
            {                   
                string DS = temp[i-1].Trim('=', ' ');
                List.Add(DS);
            }             

        }
        streamReader.Close();
    }
    catch (Exception EX)
    {
    }


    return List;

}
于 2011-11-29T07:30:10.647 回答
0

与 Sathya 提供的方法一起,创建一个方法:

StringBuilder strTns = new StringBuilder ();

foreach ( var fileLine in System.IO.File.ReadAllLines(fiTNS.FullName ) )
{
    if ( (fileLine.Length > 0 
           && fileLine.Trim().Substring(0,1) != "#" 
          )
          && ( fileLine.Length > 0 
                && fileLine.Trim ().Substring (0,1) != "/" 
              )
        )

        {
           strTns.AppendFormat("{0}{1}", fileLine, Environment.NewLine);
        }
}

//TNSNamesValues = System.IO.File.ReadAllText (fiTNS.FullName).ToString ().Replace ("\n", "" ).Replace ("\r", "");
String[] splitSeparator = LoadTNSNames (OracleHomeRegistryKey).ToArray ();
String[] TNS = strTns.ToString().Split (splitSeparator, StringSplitOptions.None);
于 2010-12-27T15:44:33.833 回答
0

这段代码对我有用,也许我们可以重构它以处理多个条目或创建可重用的函数。

    //Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=49161))(CONNECT_DATA=(SERVICE_NAME=xe)));User Id=myuser;Password=mypassword;
    var stringParts = _connectionString.Split('(');

    //HOST=localhost)
    var hostPair = stringParts.First(s => s.Contains("HOST")).Split("=");
    var host = hostPair[1].Substring(0, hostPair[1].IndexOf(")"));

    //PORT=49161)
    var portPair = stringParts.First(s => s.Contains("PORT")).Split("=");
    var port = portPair[1].Substring(0, portPair[1].IndexOf(")"));

    //SERVICE_NAME=xe)
    var serviceNamePair = stringParts.First(s => s.Contains("SERVICE_NAME")).Split("=");
    var serviceName = serviceNamePair[1].Substring(0, serviceNamePair[1].IndexOf(")"));
于 2021-12-25T03:44:35.047 回答