The name 'Server' does not exist in the current context


  • Hi everybody,

    i have a data.cs class in my login project, but this class alert me this error content on this row

    OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Server.MapPath("") + "/app_data/Akser.mdb");

    Error name: The name 'Server' does not exist in the current context


    please can anybody help me?

    Tuesday, March 20, 2007 9:42 AM

All replies

  • ASP.NET objects like Server, Profile, Session, Items, and Cache are only accessible within a Page or Control-derived class.  They are properties of the class.  Your data/business components won't have access to them.

    You can gain access to these objects (assuming they are available at the time given that they are contextual) by using the HttpContext.Current property.  This property gives you the current context.  However you are now tying your DAL/BL to ASP.NET. 

    I would recommend that you do not go the route you are going anyway as there are better methods.  You are assuming that the path to your DB won't change but this is not true.  The next version of ASP.NET might move or rename the directory.  Instead define a connection string property in your config file and use the symbolic name DataDirectory.  This isolates you from the actual path and removes the need for Server

    Do the following (since you are using an Access database).

    1. Open, or create a web.config file for your project.
    2. Add a new element in the connectionStrings section.  It will look like this:
        <add name="DbConnString" providerName="Microsoft.Jet.OLEDB.4.0" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\akser.mdb" />
    3. Modify your connection object to look like this:
         using(OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConnString"].ConnectionString))
         { ... };

    Note that some of the syntax for the connection string is because of the provider you're using.  Also be aware that if you use AccessDataSource then it does not allow you to connect to a connection string for some reason.  The other providers do.

    Michael Taylor - 3/20/07


    • Proposed as answer by xpertprogrammer Wednesday, November 09, 2011 7:45 AM
    Tuesday, March 20, 2007 2:05 PM