How do I split the text I want from a file?

Hi This is what I got in the file:

AT + CMGL = "ALL"  
+ CMGL: 6123, "REC READ", "+ 923315266206"  
B confident dat GOD can make a way wen der seems 2 b no way. Even wen your mind may waver, GOD is working bhind d scenes on yur behalf. Have a faith-filled day  
+ CMGL: 6122, "REC READ", "+ 923315266206"  
B confident dat GOD can make a way wen der seems 2 b no way. Even wen your mind may waver, GOD is working bhind d scenes on yur behalf. Have a faith-filled day

-------------------------------------------------- -------------------------------

I just want to get lines in text from a file. Like "B confidently ........ hesitate". How to do it?

I tried with splitting, but I can't get it running ..... :)

+1


a source to share


4 answers


Read the file with StreamReader and use the ReadLine method, which will read the file one line at a time.



using (StreamReader reader = File.OpenText(fileName))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        // do something with the line
    }
}

      

+4


a source


Below you will get strings to string array:

string[] lines = File.ReadAllLines(pathToFile);

      

So:



lines[2];
lines[4];

      

You will get these lines.

See the msdn documentation for ReadAllLines .

+3


a source


It looks like every line in your example that is not "valid" includes text "+CGML"

. In this case, this should do the trick:

public static IEnumerable<string> GetText(string filePath)
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        string line;
        while ( (line = sr.ReadLine()) != null)
        {
           if (line.IndexOf("+CMGL") < 0) yield return line;
        }
    }
}

      

+2


a source


Can use streamReader to read in strings and use Regex to match specific strings ... if there is a pattern you want to match.

example:

using System.IO;
using System.Text.RegularExpressions;

Regex pattern = new Regex("^B");
List<string> lines = new List<string>();
using (StreamReader reader = File.OpenText(fileName))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
         Match patternMatch = pattern.Match(blah);

            if (patternMatch.Groups.Count > 0)
            {
                lines.Add(blah);
            }
    }
}

      

0


a source







All Articles