FileSystemWatcher.Deleted Événement

Définition

Se produit quand un fichier ou un répertoire du Path spécifié est supprimé.Occurs when a file or directory in the specified Path is deleted.

public:
 event System::IO::FileSystemEventHandler ^ Deleted;
public event System.IO.FileSystemEventHandler? Deleted;
public event System.IO.FileSystemEventHandler Deleted;
[System.IO.IODescription("FSW_Deleted")]
public event System.IO.FileSystemEventHandler Deleted;
[System.IO.IODescription("Occurs when a file/directory deletion matches the filter")]
public event System.IO.FileSystemEventHandler Deleted;
member this.Deleted : System.IO.FileSystemEventHandler 
[<System.IO.IODescription("FSW_Deleted")>]
member this.Deleted : System.IO.FileSystemEventHandler 
[<System.IO.IODescription("Occurs when a file/directory deletion matches the filter")>]
member this.Deleted : System.IO.FileSystemEventHandler 
Public Custom Event Deleted As FileSystemEventHandler 

Type d'événement

FileSystemEventHandler
Attributs

Exemples

L’exemple suivant utilise l' Deleted événement pour afficher le chemin d’accès de fichier à la console chaque fois que le fichier surveillé est supprimé.The following example uses the Deleted event to display the file path to the console whenever the watched file is deleted.

#include "pch.h"

using namespace System;
using namespace System::IO;

class MyClassCPP
{
public:

    int static Run()
    {
        FileSystemWatcher^ watcher = gcnew FileSystemWatcher("C:\\path\\to\\folder");

        watcher->NotifyFilter = static_cast<NotifyFilters>(NotifyFilters::Attributes
                                                         | NotifyFilters::CreationTime
                                                         | NotifyFilters::DirectoryName
                                                         | NotifyFilters::FileName
                                                         | NotifyFilters::LastAccess
                                                         | NotifyFilters::LastWrite
                                                         | NotifyFilters::Security
                                                         | NotifyFilters::Size);

        watcher->Changed += gcnew FileSystemEventHandler(MyClassCPP::OnChanged);
        watcher->Created += gcnew FileSystemEventHandler(MyClassCPP::OnCreated);
        watcher->Deleted += gcnew FileSystemEventHandler(MyClassCPP::OnDeleted);
        watcher->Renamed += gcnew RenamedEventHandler(MyClassCPP::OnRenamed);
        watcher->Error   += gcnew ErrorEventHandler(MyClassCPP::OnError);

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

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

        return 0;
    }

private:

    static void OnChanged(Object^ sender, FileSystemEventArgs^ e)
    {
        if (e->ChangeType != WatcherChangeTypes::Changed)
        {
            return;
        }
        Console::WriteLine("Changed: {0}", e->FullPath);
    }

    static void OnCreated(Object^ sender, FileSystemEventArgs^ e)
    {
        Console::WriteLine("Created: {0}", e->FullPath);
    }

    static void OnDeleted(Object^ sender, FileSystemEventArgs^ e)
    {
        Console::WriteLine("Deleted: {0}", e->FullPath);
    }

    static void OnRenamed(Object^ sender, RenamedEventArgs^ e)
    {
        Console::WriteLine("Renamed:");
        Console::WriteLine("    Old: {0}", e->OldFullPath);
        Console::WriteLine("    New: {0}", e->FullPath);
    }

    static void OnError(Object^ sender, ErrorEventArgs^ e)
    {
        PrintException(e->GetException());
    }

    static void PrintException(Exception^ ex)
    {
        if (ex != nullptr)
        {
            Console::WriteLine("Message: {0}", ex->Message);
            Console::WriteLine("Stacktrace:");
            Console::WriteLine(ex->StackTrace);
            Console::WriteLine();
            PrintException(ex->InnerException);
        }
    }
};


int main()
{
    MyClassCPP::Run();
}
using System;
using System.IO;

namespace MyNamespace
{
    class MyClassCS
    {
        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);
            }
        }
    }
}
Imports System.IO

Namespace MyNamespace

    Class MyClassVB

        Shared Sub Main()
            Using watcher = New FileSystemWatcher("C:\path\to\folder")
                watcher.NotifyFilter = NotifyFilters.Attributes Or
                                       NotifyFilters.CreationTime Or
                                       NotifyFilters.DirectoryName Or
                                       NotifyFilters.FileName Or
                                       NotifyFilters.LastAccess Or
                                       NotifyFilters.LastWrite Or
                                       NotifyFilters.Security Or
                                       NotifyFilters.Size

                AddHandler watcher.Changed, AddressOf OnChanged
                AddHandler watcher.Created, AddressOf OnCreated
                AddHandler watcher.Deleted, AddressOf OnDeleted
                AddHandler watcher.Renamed, AddressOf OnRenamed
                AddHandler watcher.Error, AddressOf OnError

                watcher.Filter = "*.txt"
                watcher.IncludeSubdirectories = True
                watcher.EnableRaisingEvents = True

                Console.WriteLine("Press enter to exit.")
                Console.ReadLine()
            End Using
        End Sub

        Private Shared Sub OnChanged(sender As Object, e As FileSystemEventArgs)
            If e.ChangeType <> WatcherChangeTypes.Changed Then
                Return
            End If
            Console.WriteLine($"Changed: {e.FullPath}")
        End Sub

        Private Shared Sub OnCreated(sender As Object, e As FileSystemEventArgs)
            Dim value As String = $"Created: {e.FullPath}"
            Console.WriteLine(value)
        End Sub

        Private Shared Sub OnDeleted(sender As Object, e As FileSystemEventArgs)
            Console.WriteLine($"Deleted: {e.FullPath}")
        End Sub

        Private Shared Sub OnRenamed(sender As Object, e As RenamedEventArgs)
            Console.WriteLine($"Renamed:")
            Console.WriteLine($"    Old: {e.OldFullPath}")
            Console.WriteLine($"    New: {e.FullPath}")
        End Sub

        Private Shared Sub OnError(sender As Object, e As ErrorEventArgs)
            PrintException(e.GetException())
        End Sub

        Private Shared Sub PrintException(ex As Exception)
            If ex IsNot Nothing Then
                Console.WriteLine($"Message: {ex.Message}")
                Console.WriteLine("Stacktrace:")
                Console.WriteLine(ex.StackTrace)
                Console.WriteLine()
                PrintException(ex.InnerException)
            End If
        End Sub

    End Class

End Namespace

Remarques

Certaines occurrences courantes, telles que la copie ou le déplacement d’un fichier ou d’un répertoire, ne correspondent pas directement à un événement, mais ces occurrences provoquent le déclenchement des événements.Some common occurrences, such as copying or moving a file or directory, do not correspond directly to an event, but these occurrences do cause events to be raised. Lorsque vous copiez un fichier ou un répertoire, le système déclenche un Created événement dans le répertoire dans lequel le fichier a été copié, si ce répertoire est surveillé.When you copy a file or directory, the system raises a Created event in the directory to which the file was copied, if that directory is being watched. Si le répertoire à partir duquel vous avez copié a été surveillé par une autre instance de FileSystemWatcher , aucun événement n’est déclenché.If the directory from which you copied was being watched by another instance of FileSystemWatcher, no event would be raised. Par exemple, vous créez deux instances de FileSystemWatcher .For example, you create two instances of FileSystemWatcher. FileSystemWatcher1 est défini pour surveiller « C:\Mes documents » et FileSystemWatcher2 est défini pour regarder « C:\Your documents ».FileSystemWatcher1 is set to watch "C:\My Documents", and FileSystemWatcher2 is set to watch "C:\Your Documents". Si vous copiez un fichier à partir de « mes documents » vers « vos documents », un Created événement est déclenché par FileSystemWatcher2, mais aucun événement n’est déclenché pour FileSystemWatcher1.If you copy a file from "My Documents" into "Your Documents", a Created event will be raised by FileSystemWatcher2, but no event is raised for FileSystemWatcher1. Contrairement à la copie, le déplacement d’un fichier ou d’un répertoire déclenche deux événements.Unlike copying, moving a file or directory would raise two events. Dans l’exemple précédent, si vous avez déplacé un fichier de « mes documents » vers « vos documents », un Created événement est déclenché par FileSystemWatcher2 et un Deleted événement est déclenché par FileSystemWatcher1.From the previous example, if you moved a file from "My Documents" to "Your Documents", a Created event would be raised by FileSystemWatcher2 and a Deleted event would be raised by FileSystemWatcher1.

Notes

Les opérations courantes du système de fichiers peuvent déclencher plusieurs événements.Common file system operations might raise more than one event. Par exemple, lorsqu’un fichier est déplacé d’un répertoire à un autre, plusieurs OnChanged OnCreated événements et OnDeleted peuvent être déclenchés.For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Le déplacement d’un fichier est une opération complexe qui se compose de plusieurs opérations simples, déclenchant ainsi plusieurs événements.Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. De même, certaines applications (par exemple, un logiciel antivirus) peuvent provoquer des événements de système de fichiers supplémentaires qui sont détectés par FileSystemWatcher .Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

Notes

L’ordre dans lequel l' Deleted événement est déclenché par rapport aux autres FileSystemWatcher événements peut changer lorsque la SynchronizingObject propriété n’a pas la valeur null .The order in which the Deleted event is raised in relation to the other FileSystemWatcher events may change when the SynchronizingObject property is not null.

S’applique à

Voir aussi