C# how to repeat function

Viewed 62

I am reading directories and adding .ini files to listbox1 or lisbox2 depending what is inside.

    private void Form1_Load(object sender, EventArgs e)
    {
        string rootdir = @"C:\Users\isaced1\Desktop\test";   //root directory of all projects
        string[] files = Directory.GetFiles(rootdir, "*.ini", SearchOption.AllDirectories);  //searches for specific .ini files in all directories whithin rood directory

        //cycles through all .ini files and adds it to lsitbox1 or listbox2
        foreach (string item in files)
           {
            string fileContents = File.ReadAllText(item); //reads all .ini files
            const string PATTERN = @"OTPM              = true"; //search pattern in .ini files
            Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase); //matches pattern with content in .ini file

                if (match.Success)
                {
                    listBox1.Items.Add(item); //if match is successfull places file in lisbox1
                    listBox1.ForeColor = Color.Green;
                }
                else
                {
                    listBox2.Items.Add(item); //if match is unsuccessfull places file in lisbox2
                    listBox2.ForeColor = Color.Red;
                }
           }
    }

Now I want to to continuously repeat the process. I tried to do timer, but I keep getting error "error CS0120: An object reference is required for the non-static field, method, or property". I understand that my private void Form1_Load has to be static, but I just dont know way around it. My timer code

    private static System.Timers.Timer aTimer;

    public static void Main1()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 1000;
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += new ElapsedEventHandler(Form1_Load);

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;
    }

Any suggestions, thanks.

1 Answers

Don't poll for new files (using a timer is inefficient), use events from the OS to tell you when files are created/updated/deleted etc.

https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=net-6.0

    static void Main()
    {
        using var watcher = new FileSystemWatcher(@"C:\path\to\folder");

        watcher.NotifyFilter = NotifyFilters.Attributes
                             | NotifyFilters.CreationTime
                             | NotifyFilters.DirectoryName
                             | NotifyFilters.FileName
                             | NotifyFilters.LastAccess
                             | NotifyFilters.LastWrite
                             | NotifyFilters.Security
                             | NotifyFilters.Size;

        watcher.Changed += OnChanged;
        watcher.Created += OnCreated;
        watcher.Deleted += OnDeleted;
        watcher.Renamed += OnRenamed;
        watcher.Error += OnError;

        watcher.Filter = "*.txt";
        watcher.IncludeSubdirectories = true;
        watcher.EnableRaisingEvents = true;

        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (e.ChangeType != WatcherChangeTypes.Changed)
        {
            return;
        }
        Console.WriteLine($"Changed: {e.FullPath}");
    }

    private static void OnCreated(object sender, FileSystemEventArgs e)
    {
        string value = $"Created: {e.FullPath}";
        Console.WriteLine(value);
    }

    private static void OnDeleted(object sender, FileSystemEventArgs e) =>
        Console.WriteLine($"Deleted: {e.FullPath}");

    private static void OnRenamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine($"Renamed:");
        Console.WriteLine($"    Old: {e.OldFullPath}");
        Console.WriteLine($"    New: {e.FullPath}");
    }

    private static void OnError(object sender, ErrorEventArgs e) =>
        PrintException(e.GetException());

    private static void PrintException(Exception? ex)
    {
        if (ex != null)
        {
            Console.WriteLine($"Message: {ex.Message}");
            Console.WriteLine("Stacktrace:");
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine();
            PrintException(ex.InnerException);
        }
    }
Related