【问题标题】:Create XML file and when trying to add record I get error创建 XML 文件,尝试添加记录时出现错误
【发布时间】:2013-12-30 03:25:53
【问题描述】:

创建 xml 文件并写入值时出现以下错误:

'请求的操作不能在打开了用户映射部分的文件上执行。视觉工作室'

环顾互联网,有很多人遇到此错误。显然该文件并没有被释放给我然后打开它并开始向它写入记录。

我可以做些什么来确保文件被释放?

我的添加记录代码

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

我的创建文件代码

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

【问题讨论】:

  • 您是否在其他编辑器中打开了文件?
  • 尝试将代码部分从Dim sw As New StringWriter() 删除到xWrite.Close。我可以告诉它没有任何目的(您正在将XDocument 序列化为XmlWriter,但您不使用它做任何事情)。问题可能存在(但这只是猜测)。
  • 谢谢蒂姆。这样做了,但仍然是同样的错误。
  • 感谢 OldProgrammer,但该文件是在一次调用中新创建的,然后在下一次调用中添加了一条记录。
  • 您是否尝试过使用 FileStream 进行保存?通过这种方式,您可以控制流并正确关闭/刷新/处置它,并调查您或 VS 进程是否正在锁定文件。见这里msdn.microsoft.com/en-us/library/cc838476(v=vs.110).aspx 和这里stackoverflow.com/questions/9326618/…

标签: xml vb.net error-handling


【解决方案1】:

上面的 cmets 中的 Atom.gregg 发布了这个并且它起作用了。

您是否尝试过使用 FileStream 进行保存?通过这种方式,您可以控制流并正确关闭/刷新/处置它,并调查您或 VS 进程是否正在锁定文件。请参阅此处 msdn.microsoft.com/en-us/library/cc838476(v=vs.110).aspx 和此处 stackoverflow.com/questions/9326618/... – atom.gregg 1 月 2 日 14:38

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2016-07-29
    • 2014-04-21
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多