使用XML保存数据 - 另一个进程正在使用的文件

时间:2013-12-30 18:58:28

标签: xml vb.net

我是Visual Basic的新手,正在创建一个基本的任务管理器程序。我想将我的数据保存在xml文件中。

首次加载时,它会检查xml文件是否存在,如果不存在则

Private Sub frmTaskManager_Load(sender As Object, e As EventArgs) Handles Me.Load
    'Checks if tasks exists
    If IO.File.Exists("tasks.xml") Then
        GetSavedTasks()
    Else
        'Creates xml document
        CreateXMLDocument()
    End If
End Sub

Private Sub CreateXMLDocument()
        'If tasks don't exists then creates a new xml file
        Dim settings As New XmlWriterSettings()
        settings.Indent = True

        ' Initialize the XmlWriter.
        Dim XmlWrt As XmlWriter = XmlWriter.Create("Tasks.xml", settings)
        With XmlWrt
            ' Write the Xml declaration.
            .WriteStartDocument()

            ' Write a comment.
            .WriteComment("XML Database.")

            ' Write the root element.
            .WriteStartElement("Tasks")

            ' Close the XmlTextWriter.
            .WriteEndDocument()
            .Close()
        End With
    End Sub

第一次创建它时,我可以在输入任务描述后使用我的save方法添加它。这是我如何保存。

Public Sub Save()
    Dim xmlDoc As XmlDocument = New XmlDocument()
    xmlDoc.Load("Tasks.xml")

    With xmlDoc.SelectSingleNode("Tasks").CreateNavigator.AppendChild
        .WriteStartElement("task")
        .WriteElementString("description", Description)
        .WriteEndElement()
        .Flush()
        .Close()
        .Dispose()
    End With
    xmlDoc.Save("Tasks.xml")
End Sub

当xml文档不存在时,第一次一切正常。我第二次启动项目时,当我尝试添加到xml文件时,我收到错误 “mscorlib.dll

中发生了'System.IO.IOException'类型的未处理异常

其他信息:进程无法访问文件“C:\ Users \ Josh \ SkyDrive \ Projects \ Visual Basic \ Task Manager \ Task Manager \ bin \ Debug \ Tasks.xml”,因为它正由另一个进程使用。 “

任何可能导致这种情况的想法?对于VB项目来说,XML也是一个不好的选择吗?

1 个答案:

答案 0 :(得分:2)

你没有处置XmlWriter(仅仅关闭它是不够的),这就是为什么第二次触发错误(对象仍然“活着”)。 Using负责处理所有事情(处理和关闭):

 Using XmlWrt As XmlWriter = XmlWriter.Create("Tasks.xml", settings)
     With XmlWrt
         ' Write the Xml declaration.
         .WriteStartDocument()

         ' Write a comment.
         .WriteComment("XML Database.")

         ' Write the root element.
         .WriteStartElement("Tasks")

         ' Close the XmlTextWriter.
         .WriteEndDocument()
     End With
 End Using