我有一个使用xsl样式表翻译xml文件的函数。它做得很好;但是当我想删除那个转换后的文件时,有时会出现以下错误:System.IO.IOException:进程无法访问该文件
功能如下:
XslTransform transform = new XslTransform();
transform.Load('xsl_style_sheet');
transform.Transform('fullpath/xmlfilename','fullpath/transformedFileName')
XElement xEle = XElement.Load('fullpath/transformedFileName');
我用xEle做任何事情,最后我想删除'fullpath / transformedFileName',但有时我得到了可怕的System.IO.IOException:进程无法访问文件
任何人都可以帮忙。一百万谢谢
答案 0 :(得分:2)
使用XslCompiledTranform类(XslTranform is obsolete)和接受XmlReader和XmlWriter的Transform重载。您可以对它们调用Dispose,它们将负责关闭和处理基础流。
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("xsl_style_sheet");
// Create the writer.
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
using(XmlWriter writer = XmlWriter.Create("fullpath/transformedFileName", settings))
{
using(XmlReader reader = XmlReader.Create("fullpath/xmlfilename"))
{
reader.MoveToContent();
xslt.Transform(reader, writer);
}
}
using(XmlReader reader = XmlReader.Create("fullpath/transformedFileName"))
{
XElement xEle = XElement.Load(reader);
// do all other stuff you need to do here
// after this the file will be closed
}