2

I have a function that translates a xml file using a xsl style sheet. It does the job fine; but when I want to delete that transformed file sometimes I get the following error: System.IO.IOException: The process cannot access the file

The function is like this:

XslTransform transform = new XslTransform();

transform.Load('xsl_style_sheet');

transform.Transform('fullpath/xmlfilename','fullpath/transformedFileName')

XElement xEle = XElement.Load('fullpath/transformedFileName');

I do what ever with the xEle and in the end I want to delete the 'fullpath/transformedFileName' but some times i get the dreaded System.IO.IOException: The process cannot access the file

Can any one please help. A million thanks

4

1 回答 1

2

使用XslCompiledTranform类(XslTranform 已过时)和接受 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
}
于 2013-08-22T18:46:31.167 回答