-1

I am reading a text file using C# (.NET 3.5). loading file reading it line by line everything is fine working good but I want to read it from the center of a row. The Data present in .txt file is in following format:

12-09-2015 00:05:98 140.25.1.37 00120915000598  7421 03456***89 13 94569

13-09-2015 00:08:90 140.25.1.37 00130915000890     7421 034564***654 94569

13-09-2015 00:12:85 140.25.1.37 00130915001285 7421 0345***95114   94569

14-09-2015 00:11:20 140.25.1.37 00140915001120   7421 0345****9814 94569

16-09-2015 01:20:73 140.25.1.37 00160915012073     7421 03456***7698 94569

I need Data after IP 140.25.1.37..

there are more then 21000 entries in each file and data center generates like 100's of file. Please suggest me anything that is fast and efficient too.

Thank you

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92

3 Answers3

0

Try reading the file into a string and using the LastIndex method:

string readText = File.ReadAllText(filepath);  
int i = readText.LastIndexOf("140.25.1.37");

You now have the index of the last occurring ip address, and you can go from there.

SteveFerg
  • 3,466
  • 7
  • 19
  • 31
0

Since your looking for the data after that specified IP for each line, use the index of the end of the IP to grab the remaining substring.

string IP = "140.25.1.37 ";
string DataAfterIP = line.Substring(line.IndexOf(IP) + IP.Length);
0

LINQ is fun...

using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var scanPath = @"c:\your\path";
            var scanPattern = "*.log";
            var outfile = "result.log";

            var logs = from file in Directory.EnumerateFiles(scanPath, scanPattern)
                       from line in file.AsLines()
                       where line.Substring(20, 11) == "140.25.1.37"
                       select line;
            logs.WriteAsLinesTo(outfile);
        }
    }

    public static class Tools
    {
        public static void WriteAsLinesTo(this IEnumerable<string> lines, string filename)
        {
            using (var writer = new StreamWriter(filename))
                foreach (var line in lines)
                    writer.WriteLine(line);
        }

        public static IEnumerable<string> AsLines(this string filename)
        {
            using (var reader = new StreamReader(filename))
                while (!reader.EndOfStream)
                    yield return reader.ReadLine();
        }
    }
}
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69