在TXT文件c#搜索字符串 [英] c# search string in txt file
问题描述
我想找到txt文件一个字符串,如果字符串进行比较,就应该去读书,直到行我使用作为参数,另一个字符串
例如:
<预类=郎无prettyprint-覆盖>
CustomerEN //搜索此字符串
...
部分文字至极大约有顾客
ID详细信息123456
username的rootuser
...
CustomerCh //获取文本,直到这个字符串
我需要的细节,否则与他们一起工作。
我使用LINQ搜索CustomerEN是这样的:
File.ReadLines(pathToTextFile)。任何(行=> line.Contains( CustomerEN))
但现在我卡与读取线(数据),直到CustomerCh提取的细节。
如果你对线的只在您的文件中出现一次,你可以使用
File.ReadLines(pathToTextFile)
.SkipWhile(行=>!line.Contains(CustomerEN))
.Skip(1)//可选
.TakeWhile(行=> !line.Contains(CustomerCh));
如果你可以有多次出现在一个文件中,你可能最好使用普通的的foreach
循环 - 读线,保持跟踪,无论你目前的内部或客户等之外:
列表与LT;名单<串GT;>组=新的List<名单,LT;串GT;>();
名单,LT;字符串>电流=无效;
的foreach(在File.ReadAllLines(pathToFile VAR线))
{
如果(line.Contains(CustomerEN)及和放大器;当前== NULL)
电流=新的List<串GT;();
,否则如果(line.Contains(CustomerCh)及与放大器;电流!= NULL)
{
groups.Add(电流);
电流= NULL;
}
如果
current.Add(线)(电流!= NULL);
}
I want to find a string in txt file if string compares, it should go on reading lines till another string which I'm using as parameter.
Example:
CustomerEN //search for this string
...
some text wich has details about customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string
I need the details to work with them otherwise.
I'm using linq to search for "CustomerEN" like this:
File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))
But now I'm stuck with reading lines (data) till "CustomerCh" to extract details.
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular foreach
loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
这篇关于在TXT文件c#搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!