[英]Reading from a file in by specifying start point and end point
I want to read from an input file in C#. 我想从C#中的输入文件中读取。 Below is my code.
下面是我的代码。
public string ReadFromNewEntityFile()
{
string template=null;
StringBuilder s = new StringBuilder();
//char[] sourcesystemhost=null;
string inputFileName = ConfigurationManager.AppSettings["inputNewEntityFilePath"].ToString();
System.IO.StreamReader myFile;
try
{
myFile = new System.IO.StreamReader(inputFileName);
myFile.ReadLine();
while ((template = myFile.ReadLine()) != "[[END SourceSystemHost]]")
{
s.AppendLine(template);
}
}
catch (Exception ex)
{
log.Error("In Filehandler class :" + ex.Message);
throw new Exception("Input file not read" + ex.Message);
}
return template;
}
The problem is want to specify the starting point and end point for reading the contents. 问题是要指定读取内容的起点和终点。 Here I am able to specify only the end point.
在这里,我只能指定终点。 How can i specify the starting point?
如何指定起点?
Please help 请帮忙
Assuming your start/end "points" are actually lines, you basically need to read from the start and skip the lines until you reach the right one. 假设起点/终点实际上是直线,则基本上需要从头开始阅读并跳过直线,直到到达正确的直线。 Here's an easy way of doing it using
File.ReadLines
: 这是使用
File.ReadLines
的一种简单方法:
var lines = File.ReadLines(inputFileName)
.SkipWhile(line => line != "[[START SourceSystemHost]]")
.Skip(1) // Skip the intro line
.TakeWhile(line => line != "[[END SourceSystemHost]]");
You could use File.ReadLines
which does the same but more readable. 您可以使用
File.ReadLines
,它执行相同的操作但更易读。 Then use LINQ to find your start- and end-points: 然后使用LINQ查找起点和终点:
var range = File.ReadLines(inputFileName)
.SkipWhile(l => !l.TrimStart().StartsWith("[[Start SourceSystemHost]]"))
.TakeWhile(l => !l.TrimStart().StartsWith("[[END SourceSystemHost]]"));
string result = string.Join(Environment.NewLine, range);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.