views:

197

answers:

3

I have the following lines of code:

xslt.Load(XmlReader.Create(new FileStream(@"C:\website\TransList.xslt", System.IO.FileMode.Open)));

xslt.Transform(mydoc.CreateReader(),null, sw);

It works fine, if I stop the project and launch it again, I get the following error:

[System.IO.IOException] = {"The process cannot access the file 'C:\website\TransList.xslt' because it is being used by another process."}

I then have have to goto the command line and do a IISRESET to get, I can also reset the app pool, this is easiest at this time as this is just my dev box.

Now I do have the call in a try catch statement, but I cannot access the xslt object in the handler.

The xslt object doesn't seem to have a close or dispose method.

The garbage collector never gets a shot at it , it seems.

Any ideas?

+8  A: 

You will need to close your FileStream and Reader, either explicitly using .Close() or via a using statement:

using (FileStream fs = new FileStream(@"C:\website\TransList.xslt", System.IO.FileMode.Open))
   {
    xslt.Load(XmlReader.Create(fs));
    using (var reader = mydoc.CreateReader())
        {
         xslt.Transform(reader, null, sw);
        }
     }
Stuart Dunkeld
This is also a more detailed solution. Has a rating of + 6 already, answered first, giving this the answer.
James Campbell
+2  A: 

Filestream implements IDisposable and requires you to invoke Dispose to release external resources as well as implicit;y invoke close(). You should wrap your instantiation of Filestream in a using block as it ensures Dispose is invoked even if an exception is raised. To answer your question though, since you did not close the filestream, your process, presumably the w3wp.exe process still has a handle on the file stream and the only way you can release is it to reset iis or recycle the app pool. For future reference, just wrap the filestream in a using block to be safe.

Athens
+2  A: 

There is no need to explicitly create a FileStream and an XmlReader, if you know the file location then you can simply pass that to the Load method, using this overload:

XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(@"C:\website\Translist.xslt");

If you think you need to create a FileStream and an XmlReader then I agree with the suggestions already made, use the 'using' statement to properly close and dispose of those objects.

Martin Honnen
Thank you, this was the issue. I removed the filestream and that was all I needed to do. Works like a charm.
James Campbell