Keep Watch on All The File Activity in All Drives / File Monitoring Program using C#

No.of Views1168
Bookmarked0 times
Downloads 
Votes0
By  kirtan007   On  16 Feb 2010 00:02:48
Tag : CSharp , Windows Forms
Keep Watch on All The File Activity in All Drives / File Monitoring Program using C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

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 File

Thank 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


 
Sign Up to vote for this article
 
About Author
 
kirtan007
Occupation-
Company-
Member Type-Senior
Location-Not Provided
Joined date-02 Jul 2009
Home Page-http://kirtan.uni.cc
Blog Page-
He completed his Bachelor of Computer Application from Gujarat University 2009 .He is doing Master of Computer Application from Gujarat Technological University right now .. His area of Interests are Web Hacking , C# .net Windows form ,asp.net , WPF ,Silverlight ,SQL Server and Some PHP.
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top