3

In the App_Code folder, I created a new class in which I wanted to set the value of an Application State variable.

In order to read from Application State, I used the following code:

string text = (string)HttpContext.Current.Application["text"];

But now I want to set the value of the Application State. I had tried the following code, but it didn't work:

System.Web.HttpApplicationState.Application["text"] = "string";

What's the right way to set the value of an Application State variable?

Ido
  • 397
  • 2
  • 7
  • 22
  • 1
    how did you know it didn't work ? – Amit Joki Feb 15 '14 at 12:54
  • Visual Studio underlined "Application" in red, and said: "'System.Web.HttpApplicationState' does not contain a definition for 'Application'" – Ido Feb 15 '14 at 12:56
  • 1
    if I got your question correctly, why don't you use the same method of reading when you want to write? `HttpContext.Current.Session["text"] = YOUR_VALUE;` – Mohammed Swillam Feb 15 '14 at 12:58
  • From what I've read this method is for reading only. Are you sure it'll work? Visual Studio seems to accept it. – Ido Feb 15 '14 at 13:01
  • @MohammedElSayed mentioned the correct thing , you should be using either of the two for read and write. – Ram Mehta Feb 15 '14 at 13:02

3 Answers3

2

Use this:

HttpContext.Current.Application["text"] = "string";

When you are setting the value in code behind file of a page, you can simply use:

Application["text"]="string";
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

Can you please use in the following manner ?

To write the Application State as :

System.Web.HttpApplicationState.Application["text"] = "string";

And read them as

string text = (string)Application["text"];

Try this .

Ram Mehta
  • 449
  • 1
  • 6
  • 20
1

the technique to read/write application/session variables from outside your page code (say a class file) is the same, you must explicitly point to the current HTTP Context before moving forward.

as an example so to read any application variable, use the following line:

var myVariable = HttpContext.Current.Application["PROPERTY_NAME"]

and to write back a value, use the following line

HttpContext.Current.Application["PROPERTY_NAME"] = YOUR_VALUE

the same thing applies to Session variables.

P.S: I'm the one who suggested this first, see my comment above. :)

Mohammed Swillam
  • 9,119
  • 4
  • 36
  • 47