0

I am trying to read an event log from my local computer using the EventLogReader and EventRecord classes. Using C#.

I keep getting the error

CS0236 Error: A field initializer cannot reference the non-static field, method, or property 'getInfo.BSN_Navigator'

Unsure what I am doing wrong.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.Eventing.Reader;

/// </var bank>

/// </var bank>

namespace EventLogInfoReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();
            String inputString = Console.ReadLine();
        }
    }
}

public class getInfo
{
    public static PathType FilePath { get; private set; }

    EventLogReader BSN_Navigator = new EventLogReader("c:\\Users\\banvilb\\Documents\\Event Log\\FalconBackup_Sep192016T124905\\BSN_Navigator.evt", FilePath);

    EventRecord bsnRecord = BSN_Navigator.ReadEvent();

    public void getLogName()
    {
        string x = bsnRecord.LogName;
        Console.WriteLine(x);
    }

    public void getId()
    {
        int x = bsnRecord.Id;
        Console.WriteLine(x);
    }
}
Julian
  • 33,915
  • 22
  • 119
  • 174

1 Answers1

1

EventRecord bsnRecord = BSN_Navigator.ReadEvent(); needs to go in the constructor.

Fields are limited in how they can be initialized on the declaration. In your case, you are trying to call a method, but you can't call methods outside of a method. This means you need to initialize it in the constructor.

public class getInfo
{    
    EventLogReader BSN_Navigator = new EventLogReader("BSN_Navigator.evt", FilePath);

    EventRecord bsnRecord;

    public getInfo()
    {
        bsnRecord = BSN_Navigator.ReadEvent();
    }
}
TyCobb
  • 8,909
  • 1
  • 33
  • 53