Прочитать на английском

Поделиться через


EventLogEntryCollection Класс

Определение

Определяет размер и перечислители для коллекции экземпляров EventLogEntry.

public class EventLogEntryCollection : System.Collections.ICollection
Наследование
EventLogEntryCollection
Реализации

Примеры

В следующем примере показано, как получить сведения журнала событий из EventLogEntryCollection объекта .

using System;
using System.Collections;
using System.Diagnostics;

class EventLogEntryCollection_Item
{
    public static void Main()
    {
        try
        {
            string myLogName = "MyNewLog";
            // Check if the source exists.
            if (!EventLog.SourceExists("MySource"))
            {
                // Create the source.
                // An event log source should not be created and immediately used.
                // There is a latency time to enable the source, it should be created
                // prior to executing the application that uses the source.
                // Execute this sample a second time to use the new source.
                EventLog.CreateEventSource("MySource", myLogName);
                Console.WriteLine("Creating EventSource");
                Console.WriteLine("Exiting, execute the application a second time to use the source.");
                // The source is created.  Exit the application to allow it to be registered.
                return;
            }
            else
            {
                // Get the EventLog associated if the source exists.
                myLogName = EventLog.LogNameFromSourceName("MySource", ".");
            }

            // Create an EventLog instance and assign its source.
            EventLog myEventLog2 = new EventLog();
            myEventLog2.Source = "MySource";
            // Write an informational entry to the event log.
            myEventLog2.WriteEntry("Successfully created a new Entry in the Log");
            myEventLog2.Close();
            // Create a new EventLog object.
            EventLog myEventLog1 = new EventLog();
            myEventLog1.Log = myLogName;

            // Obtain the Log Entries of "MyNewLog".
            EventLogEntryCollection myEventLogEntryCollection =
               myEventLog1.Entries;
            myEventLog1.Close();
            Console.WriteLine("The number of entries in 'MyNewLog' = "
               + myEventLogEntryCollection.Count);

            // Display the 'Message' property of EventLogEntry.
            for (int i = 0; i < myEventLogEntryCollection.Count; i++)
            {
                Console.WriteLine("The Message of the EventLog is :"
                   + myEventLogEntryCollection[i].Message);
            }

            // Copy the EventLog entries to Array of type EventLogEntry.
            EventLogEntry[] myEventLogEntryArray =
               new EventLogEntry[myEventLogEntryCollection.Count];
            myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0);
            IEnumerator myEnumerator = myEventLogEntryArray.GetEnumerator();
            while (myEnumerator.MoveNext())
            {
                EventLogEntry myEventLogEntry = (EventLogEntry)myEnumerator.Current;
                Console.WriteLine("The LocalTime the Event is generated is "
                   + myEventLogEntry.TimeGenerated);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception:{0}", e.Message);
        }
    }
}

Комментарии

EventLogEntryCollection Используйте класс при чтении записей, связанных с экземпляром EventLog . Свойство Entries класса представляет собой коллекцию EventLog всех записей в журнале событий.

Так как новые записи добавляются к существующему списку, пошаговое выполнение коллекции позволяет получить доступ к записям, созданным после первоначального EventLogEntryCollectionсоздания . Однако после просмотра всего списка он не обновляется новыми записями.

Свойства

Count

Возвращает число записей в журнале событий (то есть, количество элементов коллекции EventLogEntry).

Item[Int32]

Возвращает запись в журнале событий по индексу, который начинается с 0 (нуля).

Методы

CopyTo(EventLogEntry[], Int32)

Копирует элементы коллекции EventLogEntryCollection в массив экземпляров EventLogEntry, начиная с определенного индекса массива.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Поддерживает простой итерационный перебор элементов объекта EventLogEntryCollection.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

ICollection.CopyTo(Array, Int32)

Копирует элементы коллекции в Array начиная с определенного индекса в Array.

ICollection.IsSynchronized

Получает значение, определяющее, является ли доступ к коллекции EventLogEntryCollection синхронизированным (потокобезопасным).

ICollection.SyncRoot

Возвращает объект, который позволяет синхронизировать доступ к объекту EventLogEntryCollection.

Методы расширения

Cast<TResult>(IEnumerable)

Приводит элементы объекта IEnumerable к заданному типу.

OfType<TResult>(IEnumerable)

Выполняет фильтрацию элементов объекта IEnumerable по заданному типу.

AsParallel(IEnumerable)

Позволяет осуществлять параллельный запрос.

AsQueryable(IEnumerable)

Преобразовывает коллекцию IEnumerable в объект IQueryable.

Применяется к

См. также раздел