Я пытался получить способ запуска задачи Windows в зависимости от события. Событие - это файл, который изменяется в папке. Этот файл изменяется другим процессом, который я не могу контролировать. Однако, когда этот файл меняется, мне нужно запустить определенную задачу Windows. Предпочтительно решение должно быть на C #, потому что политика в нашей компании не позволяет запускать сценарии PowerShell.

Ваша помощь будет высоко оценена.

Спасибо беки

1 ответ1

0

Я боролся с ответом на этот вопрос, и после долгих исследований я объединил информацию с моим опытом и нашел следующий ответ:

 //Purpose: Monitor changes to a folder and write to event log when a change 
 // happens. 
 //Last Mod date: 09/01/2019
 //Author: Bheki
 //Notes: The target folder is given in the parameter file. The first time the application runs must be run as an administrator.

 using System;
 using System.IO;
 using System.Security.Permissions;
 using System.Diagnostics;
 using System.Threading;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Collections.Generic;
 using System.Windows;


 public class Watcher
 {

 public static void Main()
 {


    Run();


}

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{




    // Create a new FileSystemWatcher and set its properties.
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Watcher.GetTargetFolder().Item1;
    /* Watch for changes in LastAccess and LastWrite times, and
       the renaming of files or directories. */
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    // Only watch text files.
    watcher.Filter = Watcher.GetTargetFolder().Item2;

    // Add event handlers.
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
   watcher.Deleted += new FileSystemEventHandler(OnChanged);
    //watcher.Renamed += new RenamedEventHandler(OnRenamed);

    // Begin watching.
    watcher.EnableRaisingEvents = true;

    // Wait for the user to quit the program.
    Console.WriteLine("Press \'q\' to quit the sample.");
    while (Console.Read() != 'q') ;
}

public static Tuple<string,string> GetTargetFolder()
{
    string currentRecordOpenFile;
    char ColumnDelimter = ","[0];

    string TargetFolder = "";
    string FixSelected = "";
    string FileExtension = "";
    string SecondHeader = "";

    TargetFolder = System.IO.Directory.GetCurrentDirectory().Replace("\\", "/");



    string ParameterFile = TargetFolder + "/ParameterFile.txt";
    using (StreamReader objReader = new StreamReader(ParameterFile.Replace("\\", "/")))
    {
        while (!objReader.EndOfStream)
        {
            currentRecordOpenFile = objReader.ReadLine(); //this reads a whole line of input from the file
            string[] LineOfFile = currentRecordOpenFile.Split(ColumnDelimter);
            if (LineOfFile[0] == "Pathtofiles")
            {
                //we can skip the heading
                continue;
            }
            else
            {

                    TargetFolder = LineOfFile[0].Replace("\\", "/") + "/";    //this can be changed depending on how the output looks
                    FixSelected = LineOfFile[1];
                    FileExtension = LineOfFile[2];
                    SecondHeader = LineOfFile[3];


            }

        }


        return Tuple.Create(TargetFolder, FileExtension);
    }//End of stream for reading the parameter file   
}

// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
    Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);

    string vLog = "Application";
    string vSource = "BCMPR";

    if (!EventLog.SourceExists(vSource))
    {
        //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(vSource, vLog);
        Console.WriteLine("CreatedEventSource");
        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;
    }

    // Create an EventLog instance and assign its source.



        EventLog myLog = new EventLog();
        myLog.Source = vSource;

        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        Console.WriteLine("Writting to event log");
        // Write an informational entry to the event log.    
        myLog.WriteEntry("The folder has been changed", EventLogEntryType.Information, 1307);

        System.Environment.Exit(0); 



     }


   }

В том же месте, что и приложение после того, как оно было встроено в C #. Пожалуйста, поместите файл ParameterFile.txt, и он имеет следующее содержимое:

Pathtofiles,FixSelected,FileExtension,SecondHeader
C:\Data\TEST,ALL,*.txt,TEST

Обратите внимание, что папка (C:\Data\TEST) и расширение файла (*. Txt) могут быть изменены в соответствии с требованиями пользователя.

// Средство просмотра событий Windows и настройка

После того, как этот код был запущен дважды и изменения были внесены в папку, наше событие можно увидеть в окне просмотра событий Windows. Пожалуйста, следуйте инструкциям на картинке:Журнал событий Windows и Настройка задач

Всё ещё ищете ответ? Посмотрите другие вопросы с метками .