Kevin
Kevin

Reputation: 1240

IIS Process Not Letting Go Of Files?

I have written a web app that has to save a few files. I have developed this app in C# using Visual Web Developer 2010 Express. The program executes flawlessly in VWD but when I deploy it to the server it runs into problems. One problem in particular is that the files being saved are held onto by some process and I can't access them or delete them when I need to. I believe I am properly closing the file streams. Here is an example of one such save:

string[] lines = MessagesTextbox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string messagesFileLocation = currDir + "\\" + reportDir + "\\" + messagesFile;
FileStream fs2 = File.Open(messagesFileLocation, FileMode.Create, FileAccess.Write);
using (StreamWriter sw = new StreamWriter(fs2))
{
    sw.WriteLine("<Messages>");
    foreach (string message in lines)
    {
        if (!message.Equals(""))
        {
            sw.WriteLine("\t<message>" + message + "</message>");
        }
    }
    sw.WriteLine("</Messages>");
}
fs2.Close();

The problem is also occurring when I use HtmlAgilityPack to save the rendered HTML to a file.

The only difference between my development environment and the server is that on the server my app runs under IIS. Can anyone think of a reason why this problem might occur using IIS when it doesn't occur ever in my development environment? The person who administers the server thinks it has to be my code but, like I said, it has been running for several weeks on my own machine without any of these problems.

Any suggestions are appreciated.

Regards.

Upvotes: 0

Views: 251

Answers (1)

Eric J.
Eric J.

Reputation: 150108

Your FileStream fs2 will not be closed if an Exception is thrown. You must close it in a finally block, which you get for free if you wrap it in its own using.

Everything that implements IDisposable should be wrapped in a using block (or otherwise disposed for some advanced cases) as a matter of good coding practice. There are edge cases to be sure where that does not matter, but it is a solid habit to always ensure that IDisposable.Dispose() is called as soon as an object that implements the interface is no longer required.

Upvotes: 2

Related Questions