kaka
kaka

Reputation:

How to split text I want from a file?

Hi This is Wht I got in a 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 the lines i.e text from the file.Like "B confident........waver". How do I do it ?

I tried with splitting but I cant get it running.....:)

Upvotes: 1

Views: 234

Answers (4)

CSharpAtl
CSharpAtl

Reputation: 7512

Can use the streamReader to read in the lines and use a Regex to match certain lines...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);
            }
    }
}

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

Looks like every line in your sample that is not "valid" includes the text "+CGML". In that 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;
        }
    }
}

Upvotes: 2

Oded
Oded

Reputation: 499002

The following will get you your lines into a string array:

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

So:

lines[2];
lines[4];

Will get you those lines.

See the msdn documentation for ReadAllLines.

Upvotes: 3

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

Read the file with a StreamReader and use the ReadLine method, that 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
    }
}

Upvotes: 4

Related Questions