gpt4 book ai didi

.net - 为什么 XMLWriter 没有关闭?

转载 作者:行者123 更新时间:2023-12-04 03:13:23 25 4
gpt4 key购买 nike

我在 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

最佳答案

你缺少的是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

如果您想知道这在内部是如何真正运作的,这里是 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;
}
}

关于.net - 为什么 XMLWriter 没有关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com