FileSystemWatcher.Path FileSystemWatcher.Path FileSystemWatcher.Path FileSystemWatcher.Path Property

Definición

Obtiene o establece la ruta de acceso del directorio que se va a inspeccionar.Gets or sets the path of the directory to watch.

public:
 property System::String ^ Path { System::String ^ get(); void set(System::String ^ value); };
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.IO.IODescription("The directory to monitor")]
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.IO.IODescription("FSW_Path")]
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.ComponentModel.SettingsBindable(true)]
public string Path { get; set; }
member this.Path : string with get, set
Public Property Path As String

Valor de propiedad

La ruta de acceso que se va a supervisar.The path to monitor. El valor predeterminado es una cadena vacía ("").The default is an empty string ("").

Excepciones

La ruta de acceso especificada no existe o no se encuentra.The specified path does not exist or could not be found.

o bien-or-

La ruta de acceso especificada contiene caracteres comodín.The specified path contains wildcard characters.

o bien-or-

La ruta de acceso especificada contiene caracteres de ruta de acceso no válidos.The specified path contains invalid path characters.

Ejemplos

En el ejemplo siguiente se FileSystemWatcher crea un para ver el directorio especificado en tiempo de ejecución.The following example creates a FileSystemWatcher to watch the directory specified at run time. El componente se establece para inspeccionar los cambios LastWrite en LastAccess el tiempo y la creación, la eliminación o el cambio de nombre de los archivos de texto en el directorio.The component is set to watch for changes in LastWrite and LastAccess time, the creation, deletion, or renaming of text files in the directory. Si se cambia, crea o elimina un archivo, la ruta de acceso al archivo se imprime en la consola.If a file is changed, created, or deleted, the path to the file prints to the console. Cuando se cambia el nombre de un archivo, las rutas de acceso antiguas y nuevas se imprimen en la consola.When a file is renamed, the old and new paths print to the console.

#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;

public ref class Watcher
{
private:
   // Define the event handlers.
   static void OnChanged( Object^ /*source*/, FileSystemEventArgs^ e )
   {
      // Specify what is done when a file is changed, created, or deleted.
      Console::WriteLine( "File: {0} {1}", e->FullPath, e->ChangeType );
   }

   static void OnRenamed( Object^ /*source*/, RenamedEventArgs^ e )
   {
      // Specify what is done when a file is renamed.
      Console::WriteLine( "File: {0} renamed to {1}", e->OldFullPath, e->FullPath );
   }

public:
   [PermissionSet(SecurityAction::Demand, Name="FullTrust")]
   int static run()
   {
      array<String^>^args = System::Environment::GetCommandLineArgs();

      // If a directory is not specified, exit program.
      if ( args->Length != 2 )
      {
         // Display the proper way to call the program.
         Console::WriteLine( "Usage: Watcher.exe (directory)" );
         return 0;
      }

      // Create a new FileSystemWatcher and set its properties.
      FileSystemWatcher^ watcher = gcnew FileSystemWatcher;
      watcher->Path = args[ 1 ];

      /* Watch for changes in LastAccess and LastWrite times, and 
          the renaming of files or directories. */
      watcher->NotifyFilter = static_cast<NotifyFilters>(NotifyFilters::LastAccess |
            NotifyFilters::LastWrite | NotifyFilters::FileName | NotifyFilters::DirectoryName);

      // Only watch text files.
      watcher->Filter = "*.txt";

      // Add event handlers.
      watcher->Changed += gcnew FileSystemEventHandler( Watcher::OnChanged );
      watcher->Created += gcnew FileSystemEventHandler( Watcher::OnChanged );
      watcher->Deleted += gcnew FileSystemEventHandler( Watcher::OnChanged );
      watcher->Renamed += gcnew RenamedEventHandler( Watcher::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' );

      return 0;
   }
};

int main() {
   Watcher::run();
}
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{
    public static void Main()
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void Run()
    {
        string[] args = Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if (args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = args[1];

            // 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 = "*.txt";

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += 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') ;
        }
    }

    // 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}");

    private static void OnRenamed(object source, RenamedEventArgs e) =>
        // Specify what is done when a file is renamed.
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
}
Imports System
Imports System.IO
Imports System.Security.Permissions
Imports Microsoft.VisualBasic

Public Class Watcher

    Public Shared Sub Main()

        Run()

    End Sub

    <PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
    Private Shared Sub Run()

        Dim args() As String = Environment.GetCommandLineArgs()

        ' If a directory is not specified, exit the program.
        If args.Length <> 2 Then
            ' Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)")
            Return
        End If

        ' Create a new FileSystemWatcher and set its properties.
        Using watcher As New FileSystemWatcher()
            watcher.Path = args(1)

            ' Watch for changes in LastAccess and LastWrite times, and
            ' the renaming of files or directories. 
            watcher.NotifyFilter = (NotifyFilters.LastAccess _
                                 Or NotifyFilters.LastWrite _
                                 Or NotifyFilters.FileName _
                                 Or NotifyFilters.DirectoryName)

            ' Only watch text files.
            watcher.Filter = "*.txt"

            ' Add event handlers.
            AddHandler watcher.Changed, AddressOf OnChanged
            AddHandler watcher.Created, AddressOf OnChanged
            AddHandler watcher.Deleted, AddressOf OnChanged
            AddHandler watcher.Renamed, AddressOf OnRenamed

            ' Begin watching.
            watcher.EnableRaisingEvents = True

            ' Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.")
            While Chr(Console.Read()) <> "q"c
            End While
        End Using
    End Sub

    ' Define the event handlers.
    Private Shared Sub OnChanged(source As Object, e As FileSystemEventArgs)
        ' Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}")
    End Sub

    Private Shared Sub OnRenamed(source As Object, e As RenamedEventArgs)
        ' Specify what is done when a file is renamed.
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}")
    End Sub

End Class

Comentarios

Se trata de una ruta de acceso completa a un directorio.This is a fully qualified path to a directory. Si la IncludeSubdirectories propiedad es true, este directorio es la raíz en la que el sistema inspecciona los cambios; en caso contrario, es el único directorio inspeccionado.If the IncludeSubdirectories property is true, this directory is the root at which the system watches for changes; otherwise it is the only directory watched. Para ver un archivo específico, establezca la Path propiedad en el directorio correcto completo y la Filter propiedad en el nombre de archivo.To watch a specific file, set the Path property to the fully qualified, correct directory, and the Filter property to the file name.

La Path propiedad admite rutas de acceso UNC (Convención de nomenclatura universal).The Path property supports Universal Naming Convention (UNC) paths.

Nota

Esta propiedad debe establecerse antes de que el componente pueda ver si hay cambios.This property must be set before the component can watch for changes.

Cuando se cambia el nombre de un FileSystemWatcher directorio, el se vuelve a adjuntar automáticamente al elemento que se acaba de cambiar.When a directory is renamed, the FileSystemWatcher automatically reattaches itself to the newly renamed item. Por ejemplo, si establece la Path propiedad en "c:\Mis documentos" y, a continuación, cambia manualmente el nombre del directorio a "C:\Your Documents", el componente continúa escuchando las notificaciones de cambios en el directorio cuyo nombre se acaba de cambiar.For example, if you set the Path property to "C:\My Documents" and then manually rename the directory to "C:\Your Documents", the component continues listening for change notifications on the newly renamed directory. Sin embargo, cuando se solicita la Path propiedad, contiene la ruta de acceso anterior.However, when you ask for the Path property, it contains the old path. Esto sucede porque el componente determina qué inspecciona el directorio en función del identificador, en lugar del nombre del directorio.This happens because the component determines what directory watches based on the handle, rather than the name of the directory. El cambio de nombre no afecta al identificador.Renaming does not affect the handle. Por lo tanto, si destruye el componente y, a continuación, lo vuelve a Path crear sin actualizar la propiedad, se producirá un error en la aplicación porque el directorio ya no existe.So, if you destroy the component, and then recreate it without updating the Path property, your application will fail because the directory no longer exists.

Se aplica a

Consulte también: