如何使用If Not File.Exists覆盖和现有的XML文件

时间:2012-11-19 22:12:07

标签: asp.net file exists xmlwriter

我正在尝试覆盖现有的XML文件。如果文件存在,则不会被覆盖。我在这里检查一下。为什么不被覆盖。我错过了什么?

这是我的代码

 Dim settings As New XmlWriterSettings()
        settings.Indent = True

        Dim FilePath As String = "\\server02\me_public$\audits\alert-special-reports.xml"

        If Not File.Exists(FilePath) Then
            Dim writer As XmlWriter = XmlWriter.Create(FilePath, settings)


            writer.WriteStartDocument()
            writer.WriteStartElement("audits")
            writer.WriteStartElement("alert-special-reports")
            writer.WriteElementString("title", "Alert and Special Reports")
            writer.WriteElementString("rsslink", "http://www.me.org/rss/alert-special-reports.xml")
            While dr.Read()

                writer.WriteStartElement("item")
                writer.WriteElementString("title", dr.GetString(dr.GetOrdinal("Title")))
                writer.WriteElementString("description", dr.GetString(dr.GetOrdinal("Description")))
                Dim dateNew As String = "", linkNew As String = ""
                Dim DTNew As DateTime
                Dim PDF As String = ""
                DTNew = dr.GetDateTime(dr.GetOrdinal("PubDate"))
                PDF = dr.GetString(dr.GetOrdinal("FilePath"))
                dateNew = DTNew.ToLongDateString()
                linkNew = "" & PDF & ""
                writer.WriteElementString("link", linkNew)
                writer.WriteElementString("pubdate", dateNew)
                writer.WriteEndElement()

            End While
            writer.WriteEndElement()
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Flush()
            writer.Close()
            dr.Close()
        End If

1 个答案:

答案 0 :(得分:1)

如果您忘记关闭现有的开放流,可能会发生这种情况。您可以尝试使用XMLWriter.Create的重载版本,其中stream代替string并使用File.Create方法。类似于以下内容

Dim writer As XmlWriter = XmlWriter.Create(File.Create(FilePath), settings)