The Following is the example for File System Watcher.
Create Console Application in Visual Studio.
File --> New --> Project
In the Template Select the Console Application.
Eg:
Namespaces Used:
using System.Security.Permissions;
using System.IO;
These two namespaces used for file operation and file permissions.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Permissions;
using System.IO;
namespace Watcher
{
public class Watcher
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"D:\Pilot\Sam\Projects\Watcher";
/* Watch for changes in the renaming of files. */
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.IncludeSubdirectories = false;
// Only watch txt files. This property is optional
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Created += new FileSystemEventHandler(OnCreated);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the Watcher.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnCreated(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is created.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
try
{
StreamReader reader = File.OpenText(e.FullPath);
string line = null;
while ((line = reader.ReadLine()) != null)
{
Console.Write(line + Environment.NewLine);
}
}
catch (Exception ex)
{
Console.Clear();
Console.WriteLine(ex);
}
}
}
}
Run the Console application.
It watches the path "D:\Pilot\Sam\Projects\Watcher".
Steps to watch the output.
- Create a text file with some content.
- Copy that file and paste it to your project folder.
- Then watch the output in Watcher.
Uses:
- We can upload the excel (.xls) file format via web. In the web server, the upload watcher is being run always and watching at the particular folder path.
- If any upload happens via web it can be saved in that watcher path.
- Once file uploaded, the upload watcher catches that file and performs the database actions.
Comments
Post a Comment