FileSystemWatcher.Created Evento
Definição
public:
event System::IO::FileSystemEventHandler ^ Created;
public event System.IO.FileSystemEventHandler? Created;
public event System.IO.FileSystemEventHandler Created;
[System.IO.IODescription("FSW_Created")]
public event System.IO.FileSystemEventHandler Created;
[System.IO.IODescription("Occurs when a file/directory creation matches the filter")]
public event System.IO.FileSystemEventHandler Created;
member this.Created : System.IO.FileSystemEventHandler
[<System.IO.IODescription("FSW_Created")>]
member this.Created : System.IO.FileSystemEventHandler
[<System.IO.IODescription("Occurs when a file/directory creation matches the filter")>]
member this.Created : System.IO.FileSystemEventHandler
Public Custom Event Created As FileSystemEventHandler
Tipo de evento
- Atributos
Exemplos
O exemplo a seguir usa o Created evento para exibir o caminho do arquivo para o console do sempre que o arquivo observado é criado.The following example uses the Created event to display the file path to the console whenever the watched file is created.
#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
Comentários
Algumas ocorrências comuns, como copiar ou mover um arquivo ou diretório, não correspondem diretamente a um evento, mas essas ocorrências fazem com que os eventos sejam gerados.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. Quando você copia um arquivo ou diretório, o sistema gera um Created evento no diretório no qual o arquivo foi copiado, se esse diretório está sendo observado.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. Se o diretório do qual você copiou estava sendo observado por outra instância do FileSystemWatcher , nenhum evento seria gerado.If the directory from which you copied was being watched by another instance of FileSystemWatcher, no event would be raised. Por exemplo, você cria duas instâncias do FileSystemWatcher .For example, you create two instances of FileSystemWatcher. FileSystemWatcher1 é definido para assistir a "C:\Meus documentos" e FileSystemWatcher2 está definido para assistir a "documentos C:\Your".FileSystemWatcher1 is set to watch "C:\My Documents", and FileSystemWatcher2 is set to watch "C:\Your Documents". Se você copiar um arquivo de "meus documentos" em "seus documentos", um Created evento será gerado por FileSystemWatcher2, mas nenhum evento será gerado para 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. Ao contrário da cópia, a movimentação de um arquivo ou diretório geraria dois eventos.Unlike copying, moving a file or directory would raise two events. No exemplo anterior, se você moveu um arquivo de "meus documentos" para "seus documentos", um Created evento seria gerado por FileSystemWatcher2 e um Deleted evento seria gerado por 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.
Observação
As operações comuns do sistema de arquivos podem gerar mais de um evento.Common file system operations might raise more than one event. Por exemplo, quando um arquivo é movido de um diretório para outro, vários OnChanged e alguns OnCreated OnDeleted eventos e podem ser gerados.For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Mover um arquivo é uma operação complexa que consiste em várias operações simples, gerando, portanto, vários eventos.Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Da mesma forma, alguns aplicativos (por exemplo, software antivírus) podem causar eventos de sistema de arquivos adicionais detectados pelo FileSystemWatcher .Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
Observação
A ordem na qual o Created evento é gerado em relação aos outros FileSystemWatcher eventos pode ser alterada quando a SynchronizingObject propriedade não é null .The order in which the Created event is raised in relation to the other FileSystemWatcher events may change when the SynchronizingObject property is not null.
O OnCreated evento é gerado assim que um arquivo é criado.The OnCreated event is raised as soon as a file is created. Se um arquivo estiver sendo copiado ou transferido para um diretório monitorado, o OnCreated evento será gerado imediatamente, seguido por um ou mais OnChanged eventos.If a file is being copied or transferred into a watched directory, the OnCreated event will be raised immediately, followed by one or more OnChanged events.