Search code examples
c#visual-studiofilesystemwatchersln-file

Can't use watcher.Filters.Add() function in .sln project


I am creating a project and I am using FileSystemWatcher, however I need to add multiple filters and watcher.Filters.Add() doesn't work. I am using .NET Framework ver. 4.8 and have .NET core 7.0.203 installed.

I have tried updating .NET framework. I have also created a console application which uses .NET 7.0 and .Filters.Add() works perfectly fine. Why won't it work in this code?

namespace pro
{
    public partial class Form2 : Form
    {

        public Form2()
        {
            InitializeComponent();
            comboBox1.Items.Add("Image");
            comboBox1.Items.Add("Document");
            comboBox1.Items.Add("Video");
            comboBox1.Items.Add("Audio");
            comboBox1.Items.Add("Web File");
            comboBox1.Items.Add("System File");
            comboBox1.Items.Add("Database File");
            comboBox1.Items.Add("Presentation File");
        }
        public void Vars(string text)
        {
            var path = text;
            FileSystemWatcher watcher = new FileSystemWatcher(); 
            watcher.Path = path;
            watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName;

            if (comboBox1.Text == "Image")
            {
                watcher.Filters.Add("*.txt") //why won't this work?
            }

            if (checkBox1.Checked == true)
            {
                watcher.IncludeSubdirectories = true;
            }
            else
            {
                watcher.IncludeSubdirectories = false;
            }
            watcher.Created += OnCreated;
            watcher.EnableRaisingEvents = true;

        }

        private static void OnCreated(object sender, FileSystemEventArgs file)
        {
            string value = $"Created: {file.FullPath}";
        }
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            Vars(textBox2.Text);
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}



Solution

  • Why won't it work in this code?

    FileSystemWatcher.Filters property is available since .NET Core 3.0, hence it is not available in .NET Framework. Check the Applies to section (at the moment of writing latest .NET version being ):

    Product Versions
    .NET Core 3.0, Core 3.1, 5, 6, 7, 8