Introduction
This
article will briefly explain how to create a simple "File Watcher”
application to run as a Windows Service the coding language used is C#.
Description
Use FileSystemWatcher
to watch for changes in a specified directory. You can watch for changes in
files and subdirectories of the specified directory. You can create a component
to watch files on a local computer, a network drive, or a remote computer.
Another
very useful class, FileSystemWatcher, acts as a watchdog for file system
changes and raises an event when a change occurs. You must specify a directory
to be monitored. The class can monitor changes to subdirectories and files
within the specified directory. If you have Windows 2000, you can even monitor
a remote system for changes. (Only remote machines running Windows NT or
Windows 2000 are supported at present.) The option to monitor files with
specific extensions can be set using the Filter property of the
FileSystemWatcher class
How to create a simple "File Watcher”
1) 1) First, open Visual
Studio.NET and create a new Windows Service project for C#:
2) 2) I named this sample
solution WindowsService and optionally,
chose to create a directory for the solution file.
3) 3) Next, an
appropriate reference must be added to the project as we will be using an application
configuration file. Add a reference to "System.Configuration"
by right-clicking on the project, then "Add Reference.”
4) 4) Now, add a new Application Configuration File to
the project. We will use this to define a directory (path) to
"watch":
5)
I left this named as App.config.
6)
Within the configuration which we've just added, we
will need to add an "
appSettings
"
section, where we'll define our directory path:
<appSettings>
<add key="FileWatchKey" value="D:\\Data\\" />
<add key="CreateLogfileLoc" value="D:\\Log\\" />
appSettings>
7)
We can now set up our code, controls and properties for
the actual service.
8)
First, create the main
WindowsService
component in the Service1.cs file.
This can simply be dragged and dropped from the toolbox:
9) 9) Now we can add ProjectInstaller.cs page in this page we have added two control
ServicesInstaller1 and ServicesProcessInstaller1
10 10) then write code on Service1.cs page like this
using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Diagnostics;
using
System.Linq;
using
System.ServiceProcess;
using
System.Text;
using System.IO;
using
System.Data.OleDb;
using
System.Reflection;
using
System.Data.Odbc;
using
MySql.Data.MySqlClient;
using
System.Configuration;
namespace
WindowsService
{
public partial class Service1 : ServiceBase
{
StreamWriter str;
FileStream fs = null;
FileSystemWatcher fsw = new FileSystemWatcher(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FileWatchKey"]));
public
MySql.Data.MySqlClient.MySqlConnection con;
public Service1()
{
InitializeComponent();
}
protected override void
OnStart(string[] args)
{
fsw.Filter
= "*.*";
fsw.EnableRaisingEvents
= true;
fsw.Created
+= new FileSystemEventHandler(fsw_Created);
fsw.Deleted
+= new FileSystemEventHandler(fsw_Deleted);
fsw.Renamed
+= new RenamedEventHandler(fsw_Renamed);
}
void
fsw_Renamed(Object sender, RenamedEventArgs e)
{
}
void
fsw_Deleted(Object sender, FileSystemEventArgs e)
{
}
void
fsw_Created(Object sender, FileSystemEventArgs e)
{
string
CreateLogfileLoc = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["CreateLogfileLoc"]) + "Log" + string.Concat(Convert.ToString(System.DateTime.Now.Day),
"-", Convert.ToString(System.DateTime.Now.Month), "-",
Convert.ToString(System.DateTime.Now.Year)) + ".txt";
try
{
if (!File.Exists(CreateLogfileLoc))
{
using (fs = File.Create(CreateLogfileLoc))
{
}
}
}
catch (Exception ex)
{
}
try
{
string[] varFile
= e.Name.Split('.');
string FileName =
Convert.ToString(System.Configuration.ConfigurationManager.
AppSettings["FileWatchKey"]) + e.Name;
if ((e.Name
== "Report.xls") || (e.Name == "Report.xlsx"))
{
str.WriteLine("A new file " + e.Name + " has been created in " + fsw.Path);
Microsoft.Office.Interop.Excel.Workbook theWorkbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
Microsoft.Office.Interop.Excel.Application ExcelObj = null;
Microsoft.Office.Interop.Excel.Range _range;
ExcelObj = new Microsoft.Office.Interop.Excel.Application();
theWorkbook
= ExcelObj.Workbooks._Open(FileName, 0, false,
5,
"", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t",
true, true, 0, true);
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
worksheet =
(Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
_range =
worksheet.UsedRange;
int colCount =
_range.Columns.Count;
int rowCount =
_range.Rows.Count;
System.Array myvalues = (System.Array)_range.Cells.Value2;
DataTable dt = new DataTable();
if
(myvalues.Length > 0)
{
string
strConnctivity = string.Empty;
if (rowCount
> 1)
{
dt.Rows.Clear();
dt.Columns.Clear();
DataColumn dc1 = new DataColumn("Name");
dt.Columns.Add(dc1);
for (int j = 2; j <= rowCount; j++)
{
try
{
dt.Rows.Add(CheckString(myvalues.GetValue(j,
12)));
}
catch (Exception ex)
{
}
}
}
}
ExcelObj.Workbooks.Close();
ExcelObj.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelObj);
GC.Collect();
GC.WaitForPendingFinalizers();
ExcelObj = null;
str.WriteLine("Report.xls data upload successfully");
}
}
catch (Exception ex)
{
str.WriteLine("Error in : " + e.Name + " .Error Code is:" +
ex.Message.ToString());
}
finally
{
str.Flush();
}
}
public string CheckString(object
str)
{
string
varconvertValue = Convert.ToString(str);
if
(varconvertValue == "NULL")
{
varconvertValue
= "0";
}
else if (varconvertValue == "")
{
varconvertValue
= "0";
}
return
varconvertValue;
}
}
}
Downloads
You can download the complete source code in C#
No comments :
Post a Comment