Как разобрать файл журнала событий, которого нет в системном каталоге?
Я пытаюсь разобрать файл журнала событий с помощью
System.Diagnostics.EventLog
, но то, как я разбираю журнал, мне нужно, чтобы файл. evt был в "C:\Windows\System32\winevt\Logs"
однако даже когда я запускаю программу или свою IDE в режиме администратора, она не может видеть каталог или копировать что-либо там.Итак, мой вопрос заключается в том, как мне скопировать файл в эту папку?
Или как настроить программу на поиск файлов журналов в другой папке.
public static class EventLogClassContainer { public static string EvlLocation { get; set; } = ""; public static string EvlName { get; set; } = "Application"; public static string evlLocationManual = "%Test.evt%"; public static List<EventLogEntry> _LogEntries { get; private set; } public static void ReadEventLog() { EventLog evlLog = new EventLog(EvlName, ".", @"K:\Event Log\Test\Test.evtx"); Parser.FileCopy(EvlName, EvlLocation); EventLogEntryCollection eventLogEntries = evlLog.Entries; int eventLogEntryCount = eventLogEntries.Count; _LogEntries = eventLogEntries.Cast<EventLogEntry>().ToList(); } public static void SetEvlName(string evlLocation) { Parser.FileNameFinder(evlLocation, 3); } public static void setLogLocation(string input) { EvlLocation = input; } }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { OpenFile(); } // Open the log file private void OpenFile() { // Show file open dialog if (openFile.ShowDialog() == DialogResult.OK) { // Create a dataset for binding the data to the grid. ds = new DataSet("EventLog Entries"); ds.Tables.Add("Events"); ds.Tables["Events"].Columns.Add("ComputerName"); ds.Tables["Events"].Columns.Add("EventId"); ds.Tables["Events"].Columns.Add("EventType"); ds.Tables["Events"].Columns.Add("SourceName"); ds.Tables["Events"].Columns.Add("Message"); // Start the processing as a background process EventLogClassContainer.EvlLocation = openFile.FileName; EventLogClassContainer.EvlName = System.IO.Path.GetFileName(openFile.FileName); worker.RunWorkerAsync(openFile.FileName); } }
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { EventLogClassContainer.ReadEventLog(); bs = new BindingSource(ds, "Events"); bs.DataSource = EventLogClassContainer._LogEntries; //Bind fooList to the dataGridView dataGridView1.DataSource = bs; this.dataGridView1.DataError += this.DataGridView_DataError; } void DataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e) { e.ThrowException = false; }
Что я уже пробовал:
Я попытался скопировать файл, который мне нужно прочитать, в папку, которую ищет программа, используя этот метод:
public static void FileCopy(string fileName, string sourcePath) { string targetPath = @"C:\Windows\System32\winevt\Logs"; // Use Path class to manipulate file and directory paths. string sourceFile = sourcePath; string destFile = System.IO.Path.Combine(targetPath, fileName); // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } // To copy a file to another location and // overwrite the destination file if it already exists. System.IO.File.Copy(sourceFile, destFile, true); // To copy all the files in one directory to another directory. // Get the files in the source folder. (To recursively iterate through // all subfolders under the current directory, see // "How to: Iterate Through a Directory Tree.") // Note: Check for target path was performed previously // in this code example. if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); destFile = System.IO.Path.Combine(targetPath, fileName); System.IO.File.Copy(s, destFile, true); } } else { Console.WriteLine("Source path does not exist!"); } // Keep console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.Read(); }
Но даже когда я делаю это, я получаю это исключение:
exception of type 'System.InvalidOperationException' occurred in System.dll but was not handled in user code Additional information: The event log 'Test.evt' on computer '.' does not exist.Что более или менее означает, что FileCopy не работал или, точнее, не мог найти папку, в которую я говорил ему скопировать файл.
Richard MacCutchan
Сообщение об ошибке совершенно ясно: ваша строка пути не указывает на то место, где находится файл.