Parsing tnsnames.ora in Visual C# 2008

六月ゝ 毕业季﹏ 提交于 2019-11-27 08:01:45

问题


How I parse tnsnames.ora file using Visual C# (Visual Studio 2008 Express edition) to get the tnsnames ? For instance, my tnsnames.ora file contains

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)
    )
  )

How can I parse this file to get the TNSNAMES (ie, ORCL, BILL etc). Forgive me if this question sounds too obvious, I'm learning & trying my hand in C#


回答1:


First of all, you will need the syntax rules for this file.

There is probably a hack for this, but I would personally go with a full parser, like ANTLR combined with the proper grammar (a complete list of ANTLR grammars can be found here).




回答2:


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;

}



回答3:


together with those provided by Sathya, create a method:

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);


来源:https://stackoverflow.com/questions/1243022/parsing-tnsnames-ora-in-visual-c-sharp-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!