how do i fix cannot delete file because it is being used by another process error

I have an .EXE application function function that reads files in a directory within a directory. It then pushed function to put the files in a db. then after the loadimages function does that, it loops through the directory it just loaded into the db and deletes them from the directory. Now sometimes when this exe is run there is no error, but other times there is an error. Does any body have an idea of why this is happening sometimes, but not everytime? Also, does anyone know how to fix this issue?

I am attaching the function that is receiving the error and the full error received.

FULL ERROR RECEIVED:

************ Job: Started  At Mon 04/05/2010 18:30:14.89 *********
********* Step 1: Started  At Mon 04/05/2010 18:30:15.00 *********

C:\>"\\msilsh0010V049\TAGJobs\1IAM_MailGetWork_C\MailGetWork.exe" /A ENV=Prod /A LogPath="\\msilsh0010V049\TAGJobs\1IAM_MailGetWork_C\Logs\" /A TRN=MMTG1IAMP001,11210  /A MAILSRC=\\msilsh0010V049\TagFileNet\MailWF

Unhandled Exception: System.IO.IOException: The process cannot access the file '\\msilsh0010V049\TagFileNet\MailWF\ScannedImages\LMO2010-04-05155003\INDEX.TMP' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Delete(String path)
   at MailGetWork.GetWork.deleteAllFiles(String dir)
   at MailGetWork.GetWork.LoadScannedImages(String Env, String MailSrc)
   at MailGetWork.GetWork.Main()

C:\>ECHO OFF
********* Step 1: Finished At Mon 04/05/2010 18:31:40.42 *********

FUNCTION WHERE THE ERROR IS COMING FROM

Private Function LoadScannedImages(ByVal Env As String, ByVal MailSrc As String) As Boolean
        Dim DepartmentFolder() As String
        Dim FileFolder() As String
        Dim Path As String
        Dim i As Integer
        Dim ErrorInDepartment, ErrorInScannedImages, MailDoc As Boolean

        ErrorInScannedImages = False

        Path = MailSrc & "ScannedImages"
        DepartmentFolder = Directory.GetDirectories(Path, "*")

        For i = 0 To DepartmentFolder.Length - 1
            ErrorInDepartment = False
            MailDoc = True                                              ' Some images are handled outside MailWF
            If UCase(Mid(DepartmentFolder(i), InStrRev(DepartmentFolder(i), "\") + 1, 3)) = "SBP" Then MailDoc = False
            If MailDoc Then
                ErrorInDepartment = LoadDepartmentMail(DepartmentFolder(i))

                If File.Exists(DepartmentFolder(i) & "\INDEX.DAT") Then
                    File.Delete(DepartmentFolder(i) & "\INDEX.DAT")
                End If
                If ErrorInDepartment Then
                    ErrorInScannedImages = True
                    WriteToLogFile(LogFileName, "Error in folder " & DepartmentFolder(i) & ".  Folder not processed.")
                Else
                    deleteAllFiles(DepartmentFolder(i))
                    Directory.Delete(DepartmentFolder(i))
                End If
            Else
                WriteToLogFile(LogFileName, "Bypassing " & DepartmentFolder(i))
            End If
        Next

        FileFolder = Directory.GetFiles(Path, "*")                      ' Scanner places a file in folder with
        For i = 0 To FileFolder.Length - 1                              ' stats of scan.  Don't need it so delete.
            File.Delete(FileFolder(i))
        Next

        Return ErrorInScannedImages

    End Function
bschave2Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Tarakas4Commented:
Faced a similar problem some times back. I moved the document to a temporary folder and deleted from the original folder. After processing I deleted from the temporary folder. The reason why it fails to delete sometimes is that the system could still be referring to it- perhaps you can disconnect from the database completely.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Tarakas4Commented:
Faced a similar problem some times back. I moved the document to a temporary folder and deleted from the original folder. After processing I deleted from the temporary folder. The reason why it fails to delete sometimes is that the system could still be referring to it- perhaps you can disconnect from the database completely.
rajapandian_81Commented:
Hi,

Refer below link
http://bloggingabout.net/blogs/jschreuder/archive/2006/07/06/12886.aspx

In which FileUploadCompleted function will be called with parameter filepath with filename, and it will allow access of file once it is released.
DateTime fileReceived = DateTime.Now;

    while (true)
    {
        if (FileUploadCompleted(FileName with Path here))
        {
            // Place Your Code for file delete here
            break;
        }
        // Calculate the elapsed time and stop if the maximum retry
        // period has been reached.
        TimeSpan timeElapsed = DateTime.Now - fileReceived;
        if (timeElapsed.TotalMinutes > MaximumRetryPeriod)
        {
            WriteToEventLog(string.Format(CultureInfo.CurrentCulture, "The file \"{0}\" could not be processed.", e.FullPath));
            break;
        }
        System.Threading.Thread.Sleep(RetryDelay);
    }


private static bool FileUploadCompleted(string filename)
{
    // If the file can be opened for exclusive access it means that the file
    // is no longer locked by another process.
    try
    {
        using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            return true;
        }
    }
    catch (IOException)
    {
        return false;
    }
}

Open in new window

bschave2Author Commented:
it's a false error. The directory cannot be delted if there are files in the directory. Specifically .tmp files. So, I just through a try and catch in there because if the directory doesn't delete the other automated program knows to just add more files into the directory rather than create a whole new directory. Thanks for the help though.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.