FileSystemWatcher.Created Evento

Definición

Se produce cuando se crea un archivo o un directorio en la ruta de acceso Path especificada.

C#
public event System.IO.FileSystemEventHandler? Created;
C#
public event System.IO.FileSystemEventHandler Created;
C#
[System.IO.IODescription("FSW_Created")]
public event System.IO.FileSystemEventHandler Created;

Tipo de evento

Atributos

Ejemplos

En el ejemplo siguiente se usa el Created evento para mostrar la ruta de acceso del archivo a la consola cada vez que se crea el archivo inspeccionado.

C#
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);
            }
        }
    }
}

Comentarios

Algunas repeticiones comunes, como copiar o mover un archivo o directorio, no se corresponden directamente con un evento, pero estas repeticiones hacen que se generen eventos. Al copiar un archivo o directorio, el sistema genera un Created evento en el directorio en el que se copió el archivo, si se está viendo ese directorio. Si otra instancia de FileSystemWatcherestá viendo el directorio desde el que copió, no se generaría ningún evento. Por ejemplo, se crean dos instancias de FileSystemWatcher. FileSystemWatcher1 se establece en watch "C:\My Documents" y FileSystemWatcher2 se establece en watch "C:\Your Documents". Si copia un archivo de "Mis documentos" en "Sus documentos", FileSystemWatcher2 generará un Created evento, pero no se generará ningún evento para FileSystemWatcher1. A diferencia de la copia, mover un archivo o directorio generaría dos eventos. En el ejemplo anterior, si movió un archivo de "Mis documentos" a "Sus documentos", fileSystemWatcher2 generaría un Created evento y filesystemWatcher1 generaría un Deleted evento.

Nota

Las operaciones comunes del sistema de archivos pueden generar más de un evento. Por ejemplo, cuando un archivo se mueve de un directorio a otro, se pueden generar varios OnChanged y algunos OnCreated eventos y OnDeleted . Mover un archivo es una operación compleja que consta de varias operaciones simples, por lo que genera varios eventos. Del mismo modo, algunas aplicaciones (por ejemplo, software antivirus) pueden provocar eventos adicionales del sistema de archivos detectados por FileSystemWatcher.

Nota

El orden en el que se genera el Created evento en relación con los demás FileSystemWatcher eventos puede cambiar cuando la SynchronizingObject propiedad no nulles .

El OnCreated evento se genera en cuanto se crea un archivo. Si se copia o transfiere un archivo a un directorio inspeccionado, el OnCreated evento se generará inmediatamente, seguido de uno o varios OnChanged eventos.

Se aplica a

Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Consulte también