asp.net.net-3.5iis-6xmlserializerlocked-files

IIS locking a file created by XMLWriter


I've written a .Net Web API which takes it's inputs, parses them and then stores an XML file on a network share linked to our server. I have also built a Windows service which scans the network share for new files to process our business logic.

This works nearly 100% of the time, but very occasionally (1 in 20,000 times) IIS6 holds a lock on the file it creates and won't clear until IIS is restarted. The locked files are always 0 bytes.

Currently I have a file which has been locked for nearly 20 hours! Here is the code that creates the file:

    Try
        '-- Make sure the file doesn't already exist
        TempFileName = strFullFileName
        i = 1

        While IO.File.Exists(TempFileName)
            TempFileName = strFullFileName.Replace(".xml", "_" & i & ".xml")

            i += 1
        End While

        strFullFileName = TempFileName

        '-- Deserialise the message into a file
        drSerializer = New XmlSerializer(DetailsOfMsg.GetType)
        FS = New FileStream(strFullFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
        XW = XmlWriter.Create(FS)
        drSerializer.Serialize(XW, DetailsOfMsg)

    Finally
        Try : XW.Flush() : Catch : End Try
        Try : FS.Close() : Catch : End Try
        Try : XW.Close() : Catch : End Try
        FS = Nothing
        XW = Nothing
    End Try

Why is IIS still holding a lock?


Solution

  • Did you try to wrap the code within "Using" blocks? This ensures that types of FileStream and XmlWriter get disposed once the block's scope ends.