Yarden Waizman
Yarden Waizman

Reputation: 21

Reading numbers from a text file that includes letters and numbers

I have a log file (txt file) that i want to read only specific lines from. These lines include a specific set of words followed by number.

For example, the lines that i want to read from the file read:

How do I write a code that takes only the time the query executions took (the mili) and add them up?

I got down the part of reading from the text file only the lines that include "Total query took", but I'm stuck from here

Upvotes: 1

Views: 162

Answers (3)

Riad
Riad

Reputation: 3850

This should be easy with Regular Expression. I guess the line is on a string.

String str_line = "your line from file" ;
Regex regex = new Regex(@"\d.*");
Match match = regex.Match(str_line);
if (match.Success)
{
    //you got the value with "match.Value;"
}

Upvotes: 0

Emil Lundin
Emil Lundin

Reputation: 597

public decimal ReadMilliseconds()
{
    var lines = File.ReadLines(@"\path\to\file");
    decimal totalMilliseconds = 0;

    foreach (string line in lines)
    {
        var match = Regex.Match(line, @"(?<ms>\d*\.?\d*)\s*mili");

        if (!match.Success) continue;

        decimal value = decimal.Parse(match.Groups["ms"].Value, new CultureInfo("en-US"));

        totalMilliseconds += value;
    }

    return totalMilliseconds;
}

Upvotes: 0

Peter
Peter

Reputation: 5728

  1. Read the text from the file. StreamReader can do this. Look at the example in the link.
  2. Get the number from the text. You can use Substring and IndexOf, as well as Convert.ToDouble. If you want to be fancy you can even use Regular Expressions, but this is overkill.
  3. Add the numbers.

Upvotes: 1

Related Questions