Hello-World
Hello-World

Reputation: 9545

filewatcher for newly created or altered file

How do you check for a newly created file. This only works for an edited file.

        DateTime time = DateTime.Now;             // Use current time
        string format = "dMyyyy";            // Use this format
        string s = time.ToString(format); 



        fileSystemWatcher1.Path = @"C:\Users\Desktop\test\";
        fileSystemWatcher1.NotifyFilter =   NotifyFilters.LastAccess | 
                                            NotifyFilters.LastWrite | 
                                            NotifyFilters.FileName | 
                                            NotifyFilters.DirectoryName;

        fileSystemWatcher1.IncludeSubdirectories = false;
        fileSystemWatcher1.Filter = s + ".txt";

Upvotes: 1

Views: 1150

Answers (4)

chridam
chridam

Reputation: 103325

Following the example outlined in this article C#: Application to Watch a File or Directory using FileSystem Watcher

You need to describe what has to be done when one of these attributes in fileSystemWatcher1.NotifyFilter gets altered by assigning different event handlers to different activities. For example:

fileSystemWatcher1.Changed += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Created += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Deleted += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Renamed += new RenamedEventHandler(OnRenamed);

With the signatures of both the handlers as

void OnChanged(object sender, FileSystemEventArgs e)
void OnRenamed(object sender, RenamedEventArgs e)

Example handler for OnChanged

public static void OnChanged(object source, FileSystemEventArgs e)
{
   Console.WriteLine("{0} : {1} {2}", s, e.FullPath, e.ChangeType);
}

And then enable the watcher to raise events:

fileSystemWatcher1EnableRaisingEvents = true;

Upvotes: 1

Steve
Steve

Reputation: 216243

The MSDN page is really clear on this

// Add event handlers.
fileSystemWatcher1.Created += new FileSystemEventHandler(OnChanged);

// Enable the event to be raised
fileSystemWatcher1.EnableRaisingEvents = true;

// In the event handler check the change type
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);
}

As you can see from this other page the e.ChangeType enum includes a Created value

Upvotes: 1

Kevin
Kevin

Reputation: 704

The above should work, provided you have added an event handler for fileSystemWatcher1.Created

Upvotes: 0

Amit
Amit

Reputation: 22076

You can use NotifyFilters.CreationTime for new created files as well.

NotifyFilters Enumeration

Upvotes: 1

Related Questions