EventLogEntryCollection Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет размер и перечислители для коллекции EventLogEntry экземпляров.
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
- Наследование
-
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);
}
}
}
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
End Class
Комментарии
EventLogEntryCollection Используйте класс при чтении записей, связанных с экземпляромEventLog. Свойство EntriesEventLog класса — это коллекция всех записей в журнале событий.
Так как новые записи добавляются в существующий список, пошаговое выполнение коллекции позволяет получить доступ к записям, созданным после первоначального создания 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 . |
Методы расширения
| Имя | Описание |
|---|---|
| AsParallel(IEnumerable) |
Включает параллелизацию запроса. |
| AsQueryable(IEnumerable) |
Преобразует IEnumerable в IQueryable. |
| Cast<TResult>(IEnumerable) |
Приведение элементов IEnumerable к указанному типу. |
| OfType<TResult>(IEnumerable) |
Фильтрует элементы IEnumerable на основе указанного типа. |