Glowie
Glowie

Reputation: 2309

StreamWriter doesn't create new file

Software: Visual Web Developer 2008 Express Edition Framework: ASP.NET 3.5 Language: C# Book: Programming ASP.NET 3.5

I'm trying code from the book, and it doesn't create C:\CodeLocal\test.txt as expected

global.asax

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>


<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        Application["strStartMsg"] = "The application has started.";
        string[] Books = {"SciFi","Fiction","Computers","History","Religion"};
        Application["arBooks"] = Books;
        WriteFile("Application Starting");
    }

    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
        Application["strEndMsg"] = "The application is ending.";
        WriteFile("Application Ending");
    }

    void WriteFile(string strText) {
        StreamWriter writer = new StreamWriter(@"C:\CodeLocal\test.txt",true);
        string str;
        str = DateTime.Now.ToString() + " " + strText;
        writer.WriteLine(str);
        writer.Close();
    }

</script>

Demo.aspx.cs

public partial class ApplicationStateDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0}<br/>",(string)Application["strStartMsg"]);
        sb.AppendFormat("{0}<br/>", (string)Application["strEndMsg"]);

        string[] arTest = (string[])Application["arBooks"];
        sb.AppendFormat("{0}<br/>",arTest[1].ToString());

        lblText.Text = sb.ToString();
    }
}

When I run the code my browser looks like this

enter image description here

But when I close the browser to stop execution, there is no test.txt created

The code looks correct, why isn't this working?

Upvotes: 0

Views: 353

Answers (2)

sudheeshix
sudheeshix

Reputation: 1591

Are you looking for the Session_Start and End event handlers?

The application doesnt end (and the Application_End event handler doesnt get called) when the browser is closed. The app pool has to be told to wind down in a gracious manner. This happens when the app pool recycles or shuts down after a period of inactivity.

Upvotes: 3

Pankaj Kapare
Pankaj Kapare

Reputation: 7812

Because identity under which app pool of your application is running may not have write permissions on directory C:\CodeLocal. Try giving write permissions to app pool identity on this folder.

Upvotes: 2

Related Questions