oracle 在 Visual C# 2008 中解析 tnsnames.ora
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1243022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing tnsnames.ora in Visual C# 2008
提问by Sathyajith Bhat
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
我如何使用 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)
)
)
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#
如何解析此文件以获取 TNSNAMES(即 ORCL、BILL 等)。如果这个问题听起来太明显,请原谅我,我正在学习并尝试使用 C#
采纳答案by Mac
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 ANTLRcombined with the proper grammar(a complete list of ANTLR grammars can be found here).
这可能有一个 hack,但我个人会使用完整的解析器,例如ANTLR结合正确的语法(可以在此处找到完整的 ANTLR 语法列表)。
回答by Asim Shahzad
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;
}
回答by Alcides Martínez
together with those provided by Sathya, create a method:
与 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);