C #: line = StreamReader.ReadLine <= item

1

Работа с чтением файла, отформатированного таким образом

2014/11/03 14:31:03     PID:8696        UUID:2ae855da-37d1-4a99-8510-27539afa09d0       Start   E:/I3/IC/Logs/2014-11-03/SIPEngine_2.ininlog
2014/11/04 00:00:01     PID:8696        UUID:2ae855da-37d1-4a99-8510-27539afa09d0       End     E:/I3/IC/Logs/2014-11-03/SIPEngine_2.ininlog

Я уже убираю время в переменной, но мне нужно найти файл для чего-либо, что меньше или равно значению

Благодаря @dbc

Теперь мне нужно получить матч на свидании

while (reader.next(msg, control))
{
  ActiveAttributesVect_t attribs = msg.get_active_context_attributes();
  ActiveAttributeValuesVect_t attribVals = msg.get_active_context_attribute_values();
  int numAttribs = ((attribs != null) && (attribVals != null)) ? Math.Min(attribs.Count, attribVals.Count) : 0;
  for (int i = 0; i < numAttribs; ++i)
  {
    if (attribVals[i].ToString().Contains(strCallID))
    {
      callidList.Add(msg.expand_format_message());
      // Setting the date to match the log format
      strCallDate = msg.timestamp().as_creator_time(header.tz_offset()).ToString().Substring(0, 10).Replace("-", "/");
      strCallTime = msg.timestamp().as_creator_time(header.tz_offset()).ToString().Substring(11, 8);



                    Console.WriteLine("Call Time : {0}", strCallTime);
                    Console.WriteLine("Call Date : {0}", strCallDate);
                    Console.WriteLine("");
                    foreach (var entry in callidList)
                    {
                        Console.WriteLine(entry);
                    }
                    Console.WriteLine("");


                    OutputLogLinesBeforeTime(strLogDirectory, msg.timestamp().as_creator_time(header.tz_offset()), strCallTime);

                }
            }
  • 1
    Примечание: вы не закрываете свои файлы, насколько я вижу. Вам даже не нужен StreamReader, посмотрите System.IO.File.ReadLines(string fileName) .
  • 2
    Так какой у тебя вопрос?
Показать ещё 4 комментария
Теги:
string

1 ответ

1
Лучший ответ

Вы можете использовать TimeSpan для извлечения и анализа времени суток:

    static TimeSpan? ExtractTime(string logLine)
    {
        var tokens = logLine.Split(new char [] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length < 2)
            return null;
        TimeSpan time;
        if (!TimeSpan.TryParse(tokens[1], out time))
            return null;
        return time;
    }

    static DateTime? ExtractDate(string logLine)
    {
        var tokens = logLine.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length < 1)
            return null;
        DateTime date;
        if (!DateTime.TryParse(tokens[0], out date))
            return null;
        return date;
    }

    static void OutputLogLinesBeforeTime(string strLogDirectory, string strLogDate, string strCallTime)
    {
        try
        {
            var time = TimeSpan.Parse(strCallTime);  // Throws a format exception if invalid.

            DirectoryInfo d = new DirectoryInfo(strLogDirectory + "\\" + strLogDate + "\\");

            foreach (var file in d.GetFiles("*.ininlog_journal"))
            {
                try
                {
                    using (Stream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (StreamReader sReader = new StreamReader(stream))
                    {
                        foreach (var line in sReader.EnumerateLines().Where(l => ExtractTime(l) < time))
                            Console.WriteLine(line);
                    }
                }
                catch (UnauthorizedAccessException ae)
                {
                    Console.WriteLine(ae.Message);
                }
                catch (SystemException se)
                {
                    Console.WriteLine(se.Message);
                }
                catch (ApplicationException ape)
                {
                    Console.WriteLine(ape.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
        catch (UnauthorizedAccessException ae)
        {
            Console.WriteLine(ae.Message);
        }
        catch (SystemException se)
        {
            Console.WriteLine(se.Message);
        }
        catch (ApplicationException ape)
        {
            Console.WriteLine(ape.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

Для удобства я извлек следующее:

public static class TextReaderExtensions
{
    public static IEnumerable<string> ReadLines(this TextReader sReader)
    {
        if (sReader == null)
            throw new ArgumentNullException();
        string line;
        while ((line = sReader.ReadLine()) != null)
            yield return line;
    }
}
  • 1
    попробую и дам вам знать
  • 0
    реализовал код, который вы предоставили по какой-то причине, хотя при просмотре logline здесь не выводятся строки, вот что я вижу logLine "2014/11/03 00: 00: 22 \ tPID: 4332 \ tUUID: 36515761-7ea8-4628-b137 -2b4bed4ae7e5 \ tStart \ tE: /I3/IC/Logs/2014-11-03/caasbillingserver.ininlog "string
Показать ещё 6 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню