我是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
第一次创建它时,我可以在他们输入任务描述后使用我的保存方法添加到它。 这是我的保存方式。
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 中发生了类型为'System.IO.IOException'的未处理异常.dll
其他信息:进程无法访问文件"C:\Users\Josh\SkyDrive\Projects\Visual Basic\Task Manager\Task Manager\bin\Debug\Tasks.xml,因为它正由另一个进程使用。
任何想法可能导致这种情况? 另外,XML 是否是 VB 项目存储数据的糟糕选择?
您没有处理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