문제

I want to read from an input file in 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:

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. Then use LINQ to find your start- and end-points:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top