开发者

How to read and filter lines in text file Using C#

1) I have a text file below like this.

Dilantha
code 65
po Bo 1255
colombo
sri lanka

joy
code 78
toronto
Canada

2) But I want the below result. ( I don't want the code 65 and code 78 parts)

Dilantha  colombo     sri lanka

joy       toronto     Canada

3) My requirment is, first I want to read the text file, then I want to filter the the result shown in 2 above.

Here's my Code. I'm using C#

    String line;
    String path = "c:/sample.t开发者_StackOverflowxt";

    StreamReader sr = new StreamReader(path);
    while ((line = sr.ReadLine()) != null)
    {
        //display the readed lines in the text box
        disTextBox.AppendText(line+Environment.NewLine);
    }


How about create a function to return a list of strings for one group, then maybe a class to hold the values?

public static List<string> ReadGroup(TextReader tr)
{
    string line = tr.ReadLine();
    List<string> lines = new List<string>();
    while (line != null && line.Length > 0)
    {
        lines.Add(line);
    }

    // change this to line == null if you have groups with no lines
    if (lines.Count == 0) 
    {
        return null;
    }

    return lines;
}

Then you can access the lines by index in the list:

String line;
String path = "c:/sample.txt";

using (StreamReader sr = new StreamReader(path))
{
    while ((List<string> lines = ReadGroup(sr)) != null)
    {
        // you might want to check for lines.Count >= 4 if you will
        // have groups with fewer lines to provide a better error

        //display the readed lines in the text box
        disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}",
            lines[0], lines[2], lines[3], Environment.NewLine);
    }
    sr.Close();
}

I notice that your first one has an extra line with "po Bo 1255". You need to know what format your file is to doanything meaningful. If the last two lines of a group are city and country, you need to use the count of lines. With a class:

class LineGroup // name whatever the data contains
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string City { get; set; }
    public string Country { get; set; }

    public LineGroup(List<string> lines)
    {
        if (lines == null || lines.Count < 4)
        {
            throw new ApplicationException("LineGroup file format error: Each group must have at least 4 lines");
        }

        Name = lines[0];
        Code = lines[1];
        City = lines[lines.Count - 2];
        Country = lines[lines.Count - 1];
    }
}

And to process:

while ((List<string> lines = ReadGroup(sr) != null)
{
    LineGroup group = new LineGroup(lines);

    //display the readed lines in the text box
    disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}",
        group.Name, group.City, group.Country, Environment.NewLine);
}


Use a StringBuilder to concatenate lines you read in
Use a Regex to skip over "code xx" lines
When you encounter a new line, print out what's in the StringBuilder
After you're done with the file, if you have anything left in your StringBuilder, print that out

static Regex codeRegex = new Regex("^code [\\d]+", RegexOptions.Compiled);

    static void Main(string[] args)
    {
        String line;
        String path = "c:/sample.txt";
        StringBuilder sb = new StringBuilder();

        StreamReader sr = new StreamReader(path);
        while ((line = sr.ReadLine()) != null)
        {
            line = line.Trim();

            if (codeRegex.IsMatch(line))
                continue;

            if (string.IsNullOrEmpty(line))
            {
                System.Console.Write(sb.ToString().Trim() + Environment.NewLine);
                sb.Clear();
            }
            else
            {
                sb.Append(line);
                sb.Append("\t");
            }
        }

        if (!string.IsNullOrEmpty(sb.ToString().Trim()))
            System.Console.Write(sb.ToString().Trim() + Environment.NewLine);
    }


Try it out this URL C# How to skip number of lines while reading text file using Stream Reader?


Maybe you could start with this (or something else):

foreach (var line in File.ReadLines(myFilePath)) {
  if (line.Equals("code 65") || line.Equals("code 78")) 
    continue;

  // some logic to format lines into columns....
  // ....Append(string.Format("{0, -15}{1, -15}{2, -15}", lineValue1, lineValue2, lineValue3));
}

Only works since .NET 4.0.


You can use linq to filter data. If you have the parameter you want to filter by. Hope this can help you.

  string path = "Urlfile";
  List lineas = (from l in File.ReadAllLines(path)
                         where l.Contains("parametertofilter")
                         select l).ToList();

  //test filters with linq
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜