Search code examples
c#streamreader

Reading from a file in by specifying start point and end point


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


Solution

  • 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]]");