为什么XMLWriter没有关闭?

Err*_*f1f 10 .net vb.net visual-studio-2010

我在关闭XMLWriter时遇到了一些麻烦.我可以成功写一次XML文件,但如果我再次尝试写(覆盖),我会得到异常:

"该进程无法访问文件'somefile.xml',因为它正由另一个进程使用."

    Dim settings = New XmlWriterSettings()
    settings.Indent = True
    settings.IndentChars = " "
    settings.NewLineOnAttributes = True

    Try
    Dim writer As XmlWriter = XmlWriter.Create(System.IO.File.Create("somefile.xml"))
        writer.WriteStartDocument(True)
        writer.WriteStartElement("root")
        For rowCounter As Integer = ds.Tables(0).Rows.Count - 1 To 0 Step -1
            writer.WriteStartElement("someelement")
            writer.WriteElementString("col0", ds.Tables(0).Rows(rowCounter)(0).ToString)
            writer.WriteElementString("col1", ds.Tables(0).Rows(rowCounter)(1).ToString)
            writer.WriteElementString("col2", ds.Tables(0).Rows(rowCounter)(2).ToString)
            writer.WriteElementString("col3", ds.Tables(0).Rows(rowCounter)(3).ToString)
            writer.WriteElementString("col4", ds.Tables(0).Rows(rowCounter)(4).ToString)
            writer.WriteElementString("col5", ds.Tables(0).Rows(rowCounter)(5).ToString)
            writer.WriteElementString("col6", ds.Tables(0).Rows(rowCounter)(6).ToString)
            writer.WriteElementString("col7", ds.Tables(0).Rows(rowCounter)(7).ToString)
            writer.WriteEndElement()
        Next
        writer.WriteEndElement()
        writer.WriteEndDocument()
    Catch ex As System.IO.IOException
        MessageBox.Show(ex.Message)
    Finally
        writer.Flush()
        writer.Close()
    End Try
Run Code Online (Sandbox Code Playgroud)

Abe*_*bel 15

你错过了什么,是XmlWriterSettings.您声明它,但不使用它,并且当您不CloseOutput手动设置时,默认值为false,这意味着输出未关闭(在本例中为您的文件流).

要让它按照您希望的方式运行,请更改以下代码:

Dim settings = New XmlWriterSettings()
settings.Indent = True
settings.IndentChars = " "
settings.NewLineOnAttributes = True
settings.CloseOutput = True             ' <<<< the change '

Using writer As XmlWriter = XmlWriter.Create(System.IO.File.Create("somefile.xml"), settings)
    '.... etc'
End Using
Run Code Online (Sandbox Code Playgroud)

如果你想知道它在内部是如何工作的,那么这里Close是XmlEncodedRawTextWriterIndent 的方法,它是你的场景中使用的内部XmlWriter.

// courtesy of Red Gate's Reflector
public override void Close()
{
    this.FlushBuffer();
    this.FlushEncoder();
    this.writeToNull = true;
    if (this.stream != null)
    {
        this.stream.Flush();
        if (this.closeOutput)      //this flag is set to settings.CloseOutput
        {
            this.stream.Close();
        }
        this.stream = null;
    }
    else if (this.writer != null)
    {
        this.writer.Flush();
        if (this.closeOutput)
        {
            this.writer.Close();
        }
        this.writer = null;
    }
}
Run Code Online (Sandbox Code Playgroud)