То, что вам не хватает, это 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;
}
}