EventLogEntryCollection EventLogEntryCollection EventLogEntryCollection EventLogEntryCollection Class

Определение

Определяет размер и перечислители для коллекции экземпляров EventLogEntry.Defines size and enumerators for a collection of EventLogEntry instances.

public ref class EventLogEntryCollection : System::Collections::ICollection
public class EventLogEntryCollection : System.Collections.ICollection
type EventLogEntryCollection = class
    interface ICollection
    interface IEnumerable
Public Class EventLogEntryCollection
Implements ICollection
Наследование
EventLogEntryCollectionEventLogEntryCollectionEventLogEntryCollectionEventLogEntryCollection
Реализации

Примеры

Приведенный ниже показано, как получить сведения о журнале событий из EventLogEntryCollection объекта.The following example demonstrates how to obtain event log information from an EventLogEntryCollection object.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Diagnostics;
int main()
{
   try
   {
      String^ myLogName = "MyNewLog";
      
      // Check if the source exists.
      if (  !EventLog::SourceExists( "MySource" ) )
      {
         //Create source.
         EventLog::CreateEventSource( "MySource", myLogName );
         Console::WriteLine( "Creating EventSource" );
      }
      else
            myLogName = EventLog::LogNameFromSourceName( "MySource", "." );
      
      // Get the EventLog associated if the source exists.
      // Create an EventLog instance and assign its source.
      EventLog^ myEventLog2 = gcnew 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 = gcnew EventLog;
      myEventLog1->Log = myLogName;
      
      // Obtain the Log Entries of S"MyNewLog".
      EventLogEntryCollection^ myEventLogEntryCollection = myEventLog1->Entries;
      myEventLog1->Close();
      Console::WriteLine( "The number of entries in 'MyNewLog' = {0}", myEventLogEntryCollection->Count );
      
      // Display the 'Message' property of EventLogEntry.
      for ( int i = 0; i < myEventLogEntryCollection->Count; i++ )
      {
         Console::WriteLine( "The Message of the EventLog is : {0}", myEventLogEntryCollection[ i ]->Message );
      }
      
      // Copy the EventLog entries to Array of type EventLogEntry.
      array<EventLogEntry^>^myEventLogEntryArray = gcnew array<EventLogEntry^>(myEventLogEntryCollection->Count);
      myEventLogEntryCollection->CopyTo( myEventLogEntryArray, 0 );
      IEnumerator^ myEnumerator = myEventLogEntryArray->GetEnumerator();
      while ( myEnumerator->MoveNext() )
      {
         EventLogEntry^ myEventLogEntry = safe_cast<EventLogEntry^>(myEnumerator->Current);
         Console::WriteLine( "The LocalTime the Event is generated is {0}", myEventLogEntry->TimeGenerated );
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception: {0}", e->Message );
   }
}
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);
        }
    }
}
Imports System
Imports System.Collections
Imports System.Diagnostics

Class EventLogEntryCollection_Item
   Public Shared Sub Main()
      Try
         Dim myLogName As String = "MyNewlog"
         ' Check if the source exists.
         If Not EventLog.SourceExists("MySource") Then
            'Create source.
            EventLog.CreateEventSource("MySource", myLogName)
            Console.WriteLine("Creating EventSource")
         ' Get the EventLog associated if the source exists.
         Else
            myLogName = EventLog.LogNameFromSourceName("MySource", ".")
         End If
         ' Create an EventLog instance and assign its source.
         Dim myEventLog2 As 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.
         Dim myEventLog1 As New EventLog()
         myEventLog1.Log = myLogName

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

         ' Display the 'Message' property of EventLogEntry.
         Dim i As Integer
         For i = 0 To myEventLogEntryCollection.Count - 1
            Console.WriteLine("The Message of the EventLog is :" + _
                              myEventLogEntryCollection(i).Message)
         Next i
         ' Copy the EventLog entries to Array of type EventLogEntry.
         Dim myEventLogEntryArray(myEventLogEntryCollection.Count-1) As EventLogEntry
         myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0)
         Dim myEnumerator As IEnumerator = myEventLogEntryArray.GetEnumerator()
         While myEnumerator.MoveNext()
            Dim myEventLogEntry As EventLogEntry = CType(myEnumerator.Current, EventLogEntry)
            Console.WriteLine("The LocalTime the Event is generated is " + _
                                 myEventLogEntry.TimeGenerated)
         End While
      Catch e As Exception
         Console.WriteLine("Exception:{0}", e.Message.ToString())
      End Try
   End Sub 'Main
End Class 'EventLogEntryCollection_Item

Комментарии

Используйте EventLogEntryCollection класса при чтении записи, связанные с EventLog экземпляр.Use the EventLogEntryCollection class when reading the entries associated with an EventLog instance. Entries Свойство EventLog класс — это коллекция всех записей в журнале событий.The Entries property of the EventLog class is a collection of all the entries in the event log.

Так как новые записи добавляются в существующий список, пошагового выполнения коллекции позволяет получить доступ к операции, которые были созданы после изначального создания EventLogEntryCollection.Because new entries are appended to the existing list, stepping through the collection enables you to access the entries that were created after you originally created the EventLogEntryCollection. Тем не менее после просмотра всего списка, он не обновляется новыми записями.However, after you view the entire list, it is not updated with new entries.

Свойства

Count Count Count Count

Возвращает число записей в журнале событий (то есть, количество элементов коллекции EventLogEntry).Gets the number of entries in the event log (that is, the number of elements in the EventLogEntry collection).

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

Возвращает запись в журнале событий по индексу, который начинается с 0 (нуля).Gets an entry in the event log, based on an index that starts at 0 (zero).

Методы

CopyTo(EventLogEntry[], Int32) CopyTo(EventLogEntry[], Int32) CopyTo(EventLogEntry[], Int32) CopyTo(EventLogEntry[], Int32)

Копирует элементы коллекции EventLogEntryCollection в массив экземпляров EventLogEntry, начиная с определенного индекса массива.Copies the elements of the EventLogEntryCollection to an array of EventLogEntry instances, starting at a particular array index.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Определяет, равен ли заданный объект текущему объекту.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Поддерживает простой итерационный перебор элементов объекта EventLogEntryCollection.Supports a simple iteration over the EventLogEntryCollection object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Служит хэш-функцией по умолчанию.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Inherited from Object)

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

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

Копирует элементы коллекции в Array, начиная с определенного индекса Array.Copies the elements of the collection to an Array, starting at a particular Array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

Получает значение, определяющее, является ли доступ к коллекции EventLogEntryCollection синхронизированным (потокобезопасным).Gets a value that indicates whether access to the EventLogEntryCollection is synchronized (thread-safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

Возвращает объект, который позволяет синхронизировать доступ к объекту EventLogEntryCollection.Gets an object that can be used to synchronize access to the EventLogEntryCollection object.

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

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Приводит элементы объекта IEnumerable к заданному типу.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Выполняет фильтрацию элементов объекта IEnumerable по заданному типу.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Позволяет осуществлять параллельный запрос.Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

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

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

Дополнительно