0

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.

4

1 回答 1

2

如果抛出异常,您的 FileStream fs2 将不会关闭。您必须在finally块中关闭它,如果您将其包装在自己的using中,您将免费获得该块。

作为良好的编码实践,实现IDisposable的所有内容都应包装在using块中(或以其他方式处理某些高级情况)。有一些边缘情况可以确定在哪里无关紧要,但始终确保在不再需要实现接口的对象时立即调用IDisposable.Dispose()是一个可靠的习惯。

于 2012-08-27T20:53:48.797 回答