简体   繁体   中英

Create XML file and when trying to add record I get error

When creating an xml file and writing a value I get the follwoing error:

'the requested operation cannot be performed on a file with a user-mapped section open. visual studio'

Looking around the internet there are many people getting this error. Obviously the file is not released for me to then open it and start writing records to it.

What can I do to make sure the file is released?

My Add record code

Public Function add_record_revision_number(ByVal strFile As String, strElement As String, strVersion As String, strFileName As String, strFilePath As String, strParentElement As String)

    If clsFOLDER_FUNCTIONS.FileExists(strFilePath & "\" & strFileName & ".xml") = False Then
        create_file(strFileName, strFilePath, strParentElement)
    End If



    Dim xmlDoc As XElement = XElement.Load(strFile)

    xmlDoc.Add(New XElement(strElement, _
                          New XElement("version", strVersion) _
                          ))

    xmlDoc.Save(strFile)
    xmlDoc = Nothing

    Return 0

End Function

My Create File code

Public Function create_file(ByVal strFileName As String, ByVal strFilePath As String, ByVal strParentElement As String)

    Dim empNM As XNamespace = "urn:lst-emp:emp"
    Dim xDoc As New XDocument(New XDeclaration("1.0", "UTF-16", Nothing), New XElement(empNM + strParentElement))

    Dim sw As New StringWriter()
    Dim xWrite As XmlWriter = XmlWriter.Create(sw)
    xDoc.Save(xWrite)
    xWrite.Close()

    ' Save to Disk
    xDoc.Save(strFilePath & "\" & strFileName & ".xml")
    xDoc = Nothing

    Return 0
End Function

Atom.gregg above in the comments posted this and it worked.

Have you tried using a FileStream for the save instead? This way you take control of the stream and correctly close/flush/dispose it and investigate whether you or a VS process is taking a lock on the file. See here msdn.microsoft.com/en-us/library/cc838476(v=vs.110).aspx and here stackoverflow.com/questions/9326618/… – atom.gregg Jan 2 at 14:38

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM