filewatcher for newly created or altered file - c#

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";

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;

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

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

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

Related

FileSystemWatcher does not notify on deleting the path directory itself

I am using a FileSystemWatcher in my code to track any change/rename/addition of file under the monitored directory. Now I need a notification if the monitored directory itself gets deleted.
Any suggestions on how to achieve this?
I was attempting to add a second watcher on the parent directory ( C:\temp\subfolder1 in the sample below) and filter the events to the fullpath of the monitored directory ( C:\temp\subfolder1\subfolder2).
But this won't work if the deletion is done a directory level higher and I do not want to monitor the whole file system. In the sample below it should fire on deleting C:\temp as well, not only on deleting C:\temp\subfolder1.
class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = #"C:\temp\subfolder1\subfolder2";
watcher.EnableRaisingEvents = true;
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnChanged;
Console.ReadLine();
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.FullPath);
}
}
You can subscribe to the FileSystemWatcher.Error Event. This will fire when the parent directory gets deleted. Then you can make the appropriate checks to see if this was caused by the folder deletion.
#crankedrelic Thanks for contributing!
In order to get both deletion cases (permanently and move to recycle bin) I have to use this code:
private static void OnError(object sender, ErrorEventArgs e)
{
Exception ex = e.GetException();
if (ex is Win32Exception && (((Win32Exception)ex).NativeErrorCode == 5))
{
Console.WriteLine($"Directory deleted permanently: { watcher.Path }");
}
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (!Directory.Exists(watcher.Path))
{
Console.WriteLine($"Directory deleted (recycle bin): { watcher.Path }");
}
}

FileSystemWatcher not always firing

FileSystemWatcher works if I change the file with notepad.exe, but not if I change the file with VisualStudio. Why?
See also: Powershell File Watcher Not Picking Up File Changes Made in Visual Studio
static void FileWatcher()
{
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = Path.GetDirectoryName(#"D:\Test\"),
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
Filter = "file.txt",
EnableRaisingEvents = true
};
watcher.Changed += OnFileChanged;
}
static void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} Watcher: {1} {2}", DateTime.Now, e.ChangeType, e.FullPath);
}
PS. watcher.Renamed works. Thank you mjwills.
By adding the following lines of code you should be able to capture all events.
watcher.Deleted += OnFileChanged;
watcher.Created += OnFileChanged;

Rename a file at runtime edit name , FileSystemWatcher.Renamed Event using c# window form

I'm setting a file a newName at runtime "rename " context menu strip item clicked and want to FileSystemWatcher.Renamed Event function properly
I'm trying to make File Explorer in c# window form
private void renameToolStripMenuItem_Click(object sender, EventArgs e)
{
FileSystemWatcher watcher = new FileSystemWatcher(path_textBox.Text);
//the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.Error += new ErrorEventHandler(OnError);
watcher.EnableRaisingEvents = true;
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Show that a file has been renamed.
WatcherChangeTypes wct = e.ChangeType;
MessageBox.Show($"File: {e.OldFullPath} renamed to {e.FullPath}");
}
In renameToolStripMenuItem_Click event OnRenamed event is not running after calling
You're FileSystemWatcher (FSW) is configured correctly, but you're not renaming the file and thereby the FSW isn't raising the OnRename event. Here is a quickly thrown together example that should work:
class YourClass
{
private FileSystemWatcher _watcher;
// You want to only once initialize the FSW, hence we do it in the Constructor
public YourClass()
{
_watcher = new FileSystemWatcher(path_textBox.Text);
//the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.Error += new ErrorEventHandler(OnError);
watcher.EnableRaisingEvents = true;
}
private void renameToolStripMenuItem_Click(object sender, EventArgs e)
{
// Replace 'selectedFile' and 'newFilename' with the variables
// or values you want (probably from the GUI)
System.IO.File.Move(selectedFile, newFilename);
}
private void OnRenamed(object sender, RenamedEventArgs e)
{
// Do whatever
MessageBox.Show($"File: {e.OldFullPath} renamed to {e.FullPath}");
}
// Missing the implementation of the OnError event handler
}

i want to check file exist in folder continously in c# [duplicate]

This question already has answers here:
Notification when a file changes?
(3 answers)
Closed 8 years ago.
I have requirement to process file as soon as someone put the file in ftp location
and i want to create c# code on windows server
Thanks in advance
You need to use FileSystemWatcher.
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public static void Run()
{
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;
}
// Create a new FileSystemWatcher and set its properties.
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 += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(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: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
http://www.codeproject.com/Articles/26528/C-Application-to-Watch-a-File-or-Directory-using-F

Notification when a file changes?

Is there some mechanism by which I can be notified (in C#) when a file is modified on the disc?
You can use the FileSystemWatcher class.
public void CreateFileWatcher(string path)
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
/* 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 += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// 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: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
That would be System.IO.FileSystemWatcher.
Use the FileSystemWatcher. You can filter for modification events only.

Categories

Resources