Frage

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

War es hilfreich?

Lösung

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

Andere Tipps

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);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top