473,799 Members | 2,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Windows Service File Listener

Hey all. I'm now attributing the problem I'm having to something
incredibly simple, to which I must be overlooking.

I created a Windows Service application that listens for files. The
file paths are in a config file. I then write information out to an
event log so as files are dropped into their location, I receive
information. Lastly, I wish to delete the file(s) once they are dropped
.. This is where I'm getting the awkward behavior. I get the following
exception (sometimes):

"The process cannot access the file "C:\temp\test1. txt" because it is
being used by another process."
The sometimes occurence tells me that I am either having a garbage
collection or threading problem. Here is the code I use to add the file
listener for each file:

foreach(XmlNode XNode in Config.Document Element.SelectN odes("folder"))
{
fileSystemWatch er = new System.IO.FileS ystemWatcher();

((System.Compon entModel.ISuppo rtInitialize)(t his.fileSystemW atcher)).BeginI nit();
fileSystemWatch er.Path =
Path.GetDirecto ryName(XNode.At tributes["name"].Value.ToString ());
fileSystemWatch er.Filter =
Path.GetFileNam e(XNode.Attribu tes["name"].Value.ToString ());
this.fileSystem Watcher.EnableR aisingEvents = true;
this.fileSystem Watcher.Created += new
System.IO.FileS ystemEventHandl er(this.fileSys temWatcher_Crea ted);

((System.Compon entModel.ISuppo rtInitialize)(t his.fileSystemW atcher)).EndIni t();
eventLog1.Write Entry("Adding File Watcher for " +
XNode.Attribute s["name"].Value.ToString ());
}

this code does work correctly, as the Created event does fire anytime I
add one of the files specified in the app.config file to the directory.

This is the Created event code:

private void fileSystemWatch er_Created(obje ct sender,
System.IO.FileS ystemEventArgs e)
{
eventLog1.Write Entry(e.FullPat h.ToString() + " has been delivered");
try
{
File.Delete(e.F ullPath);
}
catch (Exception ex)
{
eventLog1.Write Entry(ex.Messag e);
}
}
I got desperate and tried to invoke some garbage collection, but the
behavior did not change:

byte[] bytes = new byte[100*(1<<20)];
for(int i=0; i<bytes.Length ; i++)
bytes[i] = 0;
bytes = null;
GC.Collect();
Thread.Sleep(20 00);

Anyone out there with any ideas, I'd really appeciate it. Thanks
all!!!!

Nov 17 '05 #1
3 15803
Vinny <vi*******@gmai l.com> wrote:
Hey all. I'm now attributing the problem I'm having to something
incredibly simple, to which I must be overlooking.

I created a Windows Service application that listens for files. The
file paths are in a config file. I then write information out to an
event log so as files are dropped into their location, I receive
information. Lastly, I wish to delete the file(s) once they are dropped
. This is where I'm getting the awkward behavior. I get the following
exception (sometimes):


<snip>

The problem is just that you're getting told when the file is being
created, not when whatever's creating it has finished writing to it.

You could loop round for a few times, sleeping between attempts, until
you can delete it.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Thanks for the quick response. It turns out that the Changed event as
opposed to the Created event provides the consistency I was looking
for. Also, adding a short duration sleep command (100 ms) allowed the
service (which is multi-threaded) to relinquish control to the worker
threads. Unfortunately, using the Changed event , triggers multiple
times as the file is being written to the directory, which results in
multiple writes to the event log for a single file. Is there any way to
check when a file has completed writing after being placed in a folder?

Nov 17 '05 #3
Hi,

No really, you can do one of several things:
1- If you control the file's generator you can opt to create a "flag" file
with the same name that the output file with a different extension, and
"watch" this flag file instead of the content file itself.
2- use a timespan and ignore the events that occur before the timespan
elapse, this would prevent to process two close events.
Or a combination of both.
Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Vinny" <vi*******@gmai l.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Thanks for the quick response. It turns out that the Changed event as
opposed to the Created event provides the consistency I was looking
for. Also, adding a short duration sleep command (100 ms) allowed the
service (which is multi-threaded) to relinquish control to the worker
threads. Unfortunately, using the Changed event , triggers multiple
times as the file is being written to the directory, which results in
multiple writes to the event log for a single file. Is there any way to
check when a file has completed writing after being placed in a folder?

Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5294
by: 0to60 | last post by:
I have a windows service that when started creates two threads: one thread that runs a TcpListener waiting for TcpClients to connect, and another thread that reads from the resulting sockets. My stop code .Abort()s the threads and .Stop()s the listener. One one of my computers, the service runs like, well...a service. It starts and stops nicely. On a different computer (eventually this service will be running on 50+ machines) the...
2
1888
by: karl | last post by:
I have a windows service that kicks off a 'monitor' thread which in turn kicks off 4 additional threads. These 4 threads basically are listen on a designated socket and report back any errors (exceptions) to the monitor thread. Of course, all works well on my box. Yesterday I installed the .NET Framework 1.1 on a new server and then installed my service. It appears that everything is starting but when I perform a netstat - a...
0
1304
by: Tressa | last post by:
Sorry to be such a novice about this but..... I have a windows service. It contains two separate files. Both have the same namespace name. I need to pass "bDisplay" into the other file. I am getting several errors and not sure why or how to solve them does anyone have any help? How do I access the other file? ServerSocket.cs *This is where the main server start is so the" private bool m_bIsDisplayed = false;" had to go here so it...
4
6849
by: marc.gibian | last post by:
I am writing a small Windows Service in C#. It is structured as two C# programs, one, let's call it myAction, that runs as a command line program and a second, let's call it myWrapper, that is the actual windows service, which starts the first program as a child process (and then waits for the child process to terminate, restarting it should that ever happen). When run on its own from a shell window, myAction opens and reads its input...
2
2684
by: domtam | last post by:
Hi there. My goal is to write a windows service that can act as HTTP Request server. How can I do that? I know that I can use ASP.NET to develop a web site to achieve this purpose, i.e. receive HTTP request. However, I'd like it to exist in the form of a "Windows Service".
4
6453
by: cmgarcia17 | last post by:
I have two windows services that I've written: the first is a "Listener Service" that listens for MSMQ Message delivery. The second is a "Watcher Service" that monitors the state of the first. If the "Listener Service" goes down I want the "Watcher Service" to receive a notification and perform a set action. To enable this communication I've written a separate assembly (that both services reference) that exposes two interfaces :...
3
10357
by: jwpaco | last post by:
I am new to services and I have quite the task. I need a windows service that will, once started, open a socket and listen for client connections. When a connection is made, the client will want the service to query the db and return a value. This is for use with an IVR system. Basically, a customer will callin and request some account information and the service will need to qoery the db and return an answer to the customer through the...
4
2870
by: pbd22 | last post by:
Hi I am making my way through a windows service that accepts custom telnet commands as strings and then parses the string and redirects it. This would be a custom string sent via telnet. So, I need to prompt the user for input and then capture that imput, parse it into a form that is readable (strings in
0
1580
by: iprogrammer | last post by:
i have a problem when i try to run my windows service ..which is "Error 1053: The service did not respond to the start or control request in a timely fashion" >after this i cannot anything with the service and have to restart the computer inorder for the service to be deleted. >1) my service program is basically a client tht is listening on a port to a request from a server and establishing a new connection. 2) reading and extracting...
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10491
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10268
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10031
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9079
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.