"The process cannot access the file because it is being used by another process" in a windows service?

ipjyo
ipjyo used Ask the Experts™
on
Hi,
I am getting an error as
"The process cannot access the file because it is being used by another process"
when I was trying to drop files in a folder. My code is as shown below.
The file gets processed most of the times but sometimes I am getting the error message randomly. I am not sure how to track this.
If anybody has any idea of this, Please help me.
Thank you.
Imports System.ServiceProcess
Imports System.Threading
Imports System.Windows.Forms
Imports System.IO
Imports System.ComponentModel
Imports System.Xml
 
Namespace WatchFileSystem
    Public Class FileWatcher
        Inherits ServiceBase
 
        Private components As System.ComponentModel.IContainer = Nothing
        Private fsWatcher As FileSystemWatcher = Nothing
 
        Public Sub New()
            InitializeComponent()
        End Sub
 
        Public Shared Sub Main()
            Dim ServicesToRun As System.ServiceProcess.ServiceBase()
            ServicesToRun = New System.ServiceProcess.ServiceBase() {New FileWatcher()}
            System.ServiceProcess.ServiceBase.Run(ServicesToRun)
        End Sub
 
        Private Sub InitializeComponent()
            Me.ServiceName = "Test Service"
        End Sub
 
        Private Sub IntializeFileSystemWatcher()
            'Create File System Watcher for DAT files
            fsWatcher = New System.IO.FileSystemWatcher("C:\Sample Files", "*.DAT")
            ' Add event handlers for new files.
            AddHandler fsWatcher.Created, AddressOf OnFileCreated
            ' Begin watching.
            fsWatcher.EnableRaisingEvents = True
        End Sub
 
        Private Sub OnFileCreated(ByVal source As Object, ByVal e As FileSystemEventArgs)
            Dim ConvertXml As Translator
            ConvertXml = New Translator()
            Dim XmlDoc As New XmlDocument
            Try
                XmlDoc = ConvertXml.Prepare(e.FullPath.ToString())
                XmlDoc.Save("c:\\dynamicsample.xml")
                System.Windows.Forms.MessageBox.Show(e.FullPath.ToString(), "Success", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification)
                File.Delete(e.FullPath.ToString())
            Catch ex As Exception
                System.Windows.Forms.MessageBox.Show(ex.Message.ToString(), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification)
            End Try
        End Sub
 
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If components IsNot Nothing Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub
 
        Protected Overrides Sub OnStart(ByVal args() As String)
            IntializeFileSystemWatcher()
        End Sub
 
        'Override the OnStop method
        Protected Overrides Sub OnStop()
            'Add code to clean up or stop some things
 
        End Sub
    End Class
End Namespace

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi ipjyo,

Is this related to processing the queue every 60 seconds as well - the code looks very similar? I have a complete solution for you, if you are interested...

Thanks,

NotLogical

Author

Commented:
Hi @NotLogical,
Actually I have not tried the queue part yet. I am getting the above error sometimes when I try to place a file in that folder "C:\Sample Files". Sometimes it is working. It looks weird to me.
But if you have the code that is very helpful for me. I would appreciate if you can post the code.
Thank you
Hi ipjyo,

Here is the code. Please keep in mind the following things:
- I commented out references to "Translator" as I am not sure what assembly you used that from.
- Please remember that your output file "c:\dynamicsample.xml" will be over-written every time that a ".DAT" file gets processed: you are always writing to the same output file. It may make sense to do something like this:
   XmlDoc.Save(strQueueItem.Replace(".dat", ".xml"))
This would leave the XML file in the same folder as the DAT file, but at least it would not over-write the same file every time! :^)
- If there are files in the queue but the service is shut down, these files will not be processed. This happens because the in-memory "to be processed" queue is lost when the service is shut down.

Hope this helps you out! If you have any more questions, just ask...

Cheers,

NotLogical
Imports System.IO
Imports Microsoft.Win32
Imports System.Xml
Imports System.Threading
Imports System.Configuration
Imports System.Configuration.Install
 
 
Public Class Watcher60
    Dim qProcessList As Queue(Of String)
    Dim fsWatcher As System.IO.FileSystemWatcher
    Dim tPeriodicTimer As Timer
    Dim isServiceRunning As Boolean
    Dim tcQueueProcessor As TimerCallback
 
    Private Sub IntializeFileSystemWatcher()
        'Create File System Watcher for DAT files
        fsWatcher = New System.IO.FileSystemWatcher("C:\Sample Files", "*.DAT")
 
        ' Add event handlers for new files and change of existing files.
        'fsWatcher.Changed += new FileSystemEventHandler(OnFileChanged)
        AddHandler fsWatcher.Created, AddressOf OnFileCreated
 
        ' Begin watching.
        fsWatcher.EnableRaisingEvents = True
    End Sub
 
    Private Sub StopFileSystemWatcher()
        ' Stop watching
        fsWatcher.EnableRaisingEvents = False
    End Sub
 
    Private Sub OnFileCreated(ByVal source As Object, ByVal e As FileSystemEventArgs)
        ' Add file to our process queue
        qProcessList.Enqueue(e.FullPath)
    End Sub
    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Initialize components
        qProcessList = New Queue(Of String)
        tcQueueProcessor = New TimerCallback(AddressOf QueueProcessor)
        tPeriodicTimer = New Timer(tcQueueProcessor, Nothing, 0, 60 * 1000)
 
        ' Initialize watcher
        IntializeFileSystemWatcher()
    End Sub
 
    Protected Overrides Sub OnStop()
        ' Kill process timer
        tPeriodicTimer.Dispose()
 
        ' Kill watcher
        StopFileSystemWatcher()
 
        ' Clean-up
        qProcessList.Clear()
    End Sub
 
    Private Sub QueueProcessor(ByVal oState As Object)
        Dim strQueueItem As String
        'Dim ConvertXml As Translator
        'ConvertXml = New Translator()
 
        ' Do we have anything in the queue?
        If (qProcessList.Count = 0) Then
            Exit Sub
        End If
 
        ' Traverse queue, and process each file in turn
        Do While qProcessList.Count > 0
            strQueueItem = qProcessList.Dequeue()
 
            Dim XmlDoc As New XmlDocument
            Try
                'XmlDoc = ConvertXml.Prepare(strQueueItem)
                XmlDoc.Save("c:\\dynamicsample.xml")
                ' You may want to do this, instead...
                'XmlDoc.Save(strQueueItem.Replace(".dat", ".xml"))
                File.Delete(strQueueItem)
                System.Windows.Forms.MessageBox.Show(strQueueItem, "Processing successful!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification)
            Catch ex As Exception
                System.Windows.Forms.MessageBox.Show("File: " + strQueueItem + vbCrLf + ex.Message.ToString(), "Processing Error", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification)
            End Try
        Loop
 
    End Sub
End Class

Open in new window

OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Author

Commented:
Hi NotLogical,
Thank you very much for your help and suggestions.
It is good to have this
XmlDoc.Save(strQueueItem.Replace(".dat", ".xml"))
This is what I actually wanted.
And please give me sometime to implement the above code. I will get back to you.
Thanks again!

Author

Commented:
Hi @NotLogical,
Your code is working exactly how I wanted.
Thanks very much
You're very welcome! Glad I could assist!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial