Parsing tnsnames.ora in Visual C# 2008
-
12-09-2019 - |
Question
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#
Solution
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).
OTHER TIPS
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;
}
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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow