Introduction
Somtime you require code for watching Perticulaer Files under perticular Directory( Weather file is Deleted ,Renamed or New file is Created Under that Directory?) this type of coding normally used in antivirus programs antivirus program scans the file when new file is created,or deleted or renamed .this is what they call realtime scanning.
so here the code explained how to do Watch on All the HardDrive File changes in the System and Writing it in Log file . In most of the Code part i have commnted what the code does .
Technologies:
.net 2.0/3.5
Language:
C#
Prerequisite
* .NET Framework 2.0/3.5 * Visual Studio 2005/2008 * Event Handling in C#
Implementation
Prjects is All about Dealing with Files so First of All Add {codecitation class="brush: csharp; gutter: true;" width="650px"} using System.IO; {/codecitation}
for this Code We use main two user defined functions those are WriteLog() and StartMonitoring() WriteLog() Function Function will Write the Log in log.txt file which is located where the Program exe is Stored {codecitation class="brush: csharp; gutter: true;" width="650px"}
public void WriteLog(string s) { // Get the Exact Location of the textFile
string LogFilePath = Directory.GetParent(Application.ExecutablePath).ToString() + @"\Log.txt"; //Create the StremWriter Object with FileName as Constuctor Argument and the Second Parameter is For Weather Text is Appnded or Not StreamWriter sw = new StreamWriter(LogFilePath, true); // Write The Line to TextFile sw.WriteLine(s); // Close the Stream Write After Writing sw.Close(); }
{/codecitation}
Now the main function of the Program that is StartMonitoring() function First Checks Wearther Log file is Exist or Not and if Not then It Will create one and Write Current Date Time in it.
Now Take a Look At What The StartMonitoring() Function Do...
{codecitation class="brush: csharp; gutter: true;" width="650px"}
public void StartMonitoring() {
// Check Waeather Logfile is Already Exist or Not and If Not then Create one string Path = Directory.GetParent(Application.ExecutablePath).ToString() + @"\Log.txt"; if (File.Exists(Path) == false ) { StreamWriter sw = new StreamWriter(Path); // Write Current Date time to File sw.WriteLine(DateTime.Now.ToString()); sw.Close(); } //Get all Drives of Computer DriveInfo[] dinfo = DriveInfo.GetDrives(); Loop Through All The Drives
foreach (DriveInfo d in dinfo) { // Allocate Each FileWatcher a RootDirectory of Drive to Watch Here We have used Try catch Beacause //Some Drive like RamDrive unknown Drive will trow Exception and We need to handle it try { // Create the Instance of the File System Watcher FileSystemWatcher fsw = new FileSystemWatcher(d.RootDirectory.ToString()); fsw.EnableRaisingEvents = true; // FileWatcher Will Watch the subfolder of Drives Root Directory too fsw.IncludeSubdirectories = true; // Now Create three Event handlers Here perpose of Addind Event handles Programmatically is We dont know the number of Drives // User having in Computer so Code will generate FileWatcher object as many as the using Having Drive and Watch on all The Drives
// Event Handler for Handling FileRename Event fsw.Renamed += new RenamedEventHandler(FileRenamed);
//Eventhandler for File Created Event fsw.Created += new FileSystemEventHandler(FileCreated);
//EventHandler for File delete Event fsw.Deleted += new FileSystemEventHandler(FileDeleted); } catch { } } } {/codecitation} Define all the methods that We have Defined in Event handles
{codecitation class="brush: csharp; gutter: true;" width="650px"}
// Procedure to do When File Renaming take Place public void FileRenamed(Object Sender, RenamedEventArgs e) { // Write the Log to Text File WriteLog(e.OldFullPath + "Renamed to " + e.Name); }
// Procedure to do When File is Created public void FileCreated(Object Sender, FileSystemEventArgs e) { WriteLog("Created File " + e.FullPath); } // Procedure to do When File is Created public void FileDeleted(Object Sender, FileSystemEventArgs e) { WriteLog("Deleted File :" + e.FullPath); }
{/codecitation} Now Mostly Things of the Code is Done
Now Simple Call The StartMonitoring() Function in Form Load Event and you are Done !! {codecitation class="brush: csharp; gutter: true;" width="650px"}
private void Form1_Load(object sender, EventArgs e) { StartMonitoring(); } {/codecitation} Conclusion
Article explains How to Handle Events Raised when some fileHandling operation done in the System using FileSystemWatcher.
Extra Info * You can Add time Stamp While Some Event Occur use DateTime.Now to Achieve it * Most of this Type of Application Run In background if you Want to make it Work in Hiden Mode then you can meke it Hidden By Using Win32API Function ShowWindow() you will See my Article on Common Win32 API function soon .. Review my article and put comment !! You can also download Project Files Attached to See the Working Project Download Project FileThank you
| About the Author |
 | | Kirtan Patel | - Bachelor of Computer Application . - File Handling with C# - Registry Programming With C#. - Knowledge of Virus Programming . - Working With third party controls like Telerik and Component Factory . - P/invoke Win32 API. - SQL Server Database Applications - Client/Server Database Programming Expertise in : C# , Asp.net ,Vb.net , SQL Server , Designing Elegant look Web interface Familiar With : C/C++ , Core Java , Java Script , Dream weaver templates , fire Works , Photo shop Graphics ,PHP Databases: Microsoft SQL Server 2005 , Microsoft Access and Some MySQL Occupation: Student
|
|
|