Use HttpContext and Server.MapPath in a C# class library

Posted: May 30, 2008 in C#
Tags: ,

When I faced this problem, I hardly find proper solution on net (May be my search keywords are not capable of finding proper solution). So, I decided to let everybody know how we can use HttpContext and Server.MapPath in a C# class library. You can also use Session, and Application State, Server, Request and Response objects by just adding reference of System.Web.dll from .NET framework into your C# library Reference and include that namespace in your class file at the beginning like:

using System.Web;

Whether you found this article useful or not? please provide your valuable comments.

Comments
  1. Needhi says:

    Hi.. i already have added reference of system.web.dll in my .net application and have added its namespace in .cs file bt den also wen i use server.Mappath or Response object , it says ‘it does not exist in current context’ .. can u suggest me some soln to this problem.. thnx in advance…

  2. hspinfo says:

    Hi Needhi,

    Don’t try alone “Server.Mappath();”

    Try using “System.Web.HttpContext.Current.Server.MapPath();”

    • Harish says:

      Dear Freind,

      I tried this line,

      System.Web.HttpContext.Current.Server.MapPath()

      But it gives following error,

      Object reference not set to an instance of an object.

      Can u plz tell me how to solve this problem ?

      Thnks
      Harish

      • rodrigo says:

        have you found the solution? i have the same problem…

        System.Web.HttpContext.Current.Server.MapPath()

        gives me the same error as you…

    • Mahesh says:

      Responses to “Use HttpContext and Server.MapPath in a C# class library”

      • Gaurav says:

        HttpContext.Current.Server.MapPath() doesnt work at my end… can you please expalin/share teh code line for the same….

    • Sunandan Dutt says:

      Good Answer. Really Works.

  3. Needhi says:

    Hi..
    thnx dat wrked…

  4. Satia says:

    Thanks , hspInfo ….

    Thanks a lot …

  5. Anant Patil says:

    Thanks All.
    This Help me a lot.

    Anant Patil

  6. WebDeveloper says:

    Thank you very much hspinfo!
    its working

  7. jegathees says:

    Hey its great…
    thanks a lot…..

  8. meenakshi says:

    I am not able to use HttpContext in my class. please help

  9. kanchan says:

    thnx …..it works 🙂

  10. yashoda says:

    hi……..
    i m new to asp.net…….
    i wanted to knw how to giv the server.mappath…..
    String connectionstring=”Provider=Microsoft.Jet.OLEDB.4.0;”+”DataSource=”+Server.MapPath(“C://Documents and Settings/yashoda.gm.SYSTEM12/My Documents/Visual Studio Projects/test4/PersonalDetails1.xls”)+”;”+”Extended Properties=Excel 8.0″;

    but i m gettin error………invalid path for mappath…virtual path is expected…..plz guide me……

  11. Ronaldo Canesqui says:

    Thanks a lot !!!!!

  12. shirsendu says:

    thanks its realy worked.

  13. gopal says:

    hi,

    how can i use Server.Mappath in C# winforms

    gopal

  14. Sundance says:

    Ok, here’s my code:

    Ignite.Web.Config.SiteDynamics sd = new Ignite.Web.Config.SiteDynamics(Server.MapPath(“~/hcp/config/site.config”));

    Is there any way to declare the mappath WITHOUT the Ignite code? I’m relatively junior when it comes to this stuff…

  15. almny says:

    thanks this working good
    System.Web.HttpContext.Current.Server.MapPath()

  16. skeet says:

    what if you’re working with a windows form control? there’s no httpcontext. i’m trying to find the physical path of web folders in ‘my network places’ so i can get file sizes

  17. SeCToR says:

    Excellent man, it’s work!!

    HttpContext.Current.Server.MapPath()

  18. nitu says:

    thank you so much

    u have done such a nice job.

    u solved my query that , i was trying to solved since very long time

    once again thank you so much : )

  19. celio says:

    Nice! thanks!!!

  20. Varun Sareen says:

    Dear Friends,

    I want to open a file on the click of a link in the Grid named as VIEW. The path I am binding to is the local path i.e., ~/Documents/ScanDoc/[FileName] but when i am opening it on the local server; I am getting the error as follows:-

    File does not exist.
    System.Web.HttpException: File does not exist. at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response) at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context) at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

    But when I updated the PathColumn in database with this value:-“http://localhost:1383/~/Document/ScanDoc/[FileName]” which is actually being saved as “Documents/ScanDoc/[FileName]”, the thing worked and i was able to see the file when i clicked on the link.

    Now my problem is that how could i bind “http://localhost:1383/~” path to “Documents/ScanDoc/[FileName]” which is being saved in the database.

  21. correction says:

    You don’t need to make it into a session. You can just write
    HttpContext.Current.Server.MapPath

  22. Devender Maragani says:

    great it working HttpContext.Current.Server.MapPath(FileName)

  23. chetan says:

    how to use server.map path in web.config file…
    i m using class file to assign database connection..

  24. justus says:

    hi,

    It is working outside App_Code folder…

    but when I tried to use HttpContext inside App_Code, Intellisense is not supporting….

  25. Vishnu says:

    I tried this line,

    System.Web.HttpContext.Current.Server.MapPath()

    But it gives following error,

    Object reference not set to an instance of an object.

    Can u plz tell me how to solve this problem ?

  26. Vishnu says:

    System.Web.HttpContext.Current.Server.MapPath(filename)

    But it gives following error,

    Object reference not set to an instance of an object.

    Can u plz help me ?

  27. Vishnu says:

    hi friends,

    i used an xml file write in one aspx file

    now i need to read the content of those xml file in .cs(class file)

    But it gives following error,

    Object reference not set to an instance of an object

    while using this code

    System.Web.HttpContext.Current.Server.MapPath()

    • kailash says:

      using System.Web;
      Take the reference of System.Web in the project where ever you want to refer it and the add above as in the library then call System.Web.HttpContext.Current.Server.MapPath();

      it will works.

      thanks
      kailash

  28. Tan Thuc says:

    string cnStr = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” +System.Web.HttpContext.Current.Server.MapPath(“.”).ToString() + “\\BanHang.accdb” + “;Jet OLEDB:Database Password=12345”;

  29. Tim says:

    Thanks for the helpful infomation. 🙂

  30. Trev says:

    Hi, If you are all getting “object reference not set…” that’s probably because you need to first initialise a new instance of the class. Here’s my working code for writing to an error file in a folder on my server:

    in your class.cs file have something like the following :

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.IO;

    ///
    /// Summary description for errorfile
    ///
    public class errorFile
    {
    string dateTime = DateTime.Now.ToString(“dd-MM-yyyy_HH-mm”);

    public string errorfile()
    {
    string logfileError = Path.Combine((HttpContext.Current.Server.MapPath(“Feedback_Log_file”)), dateTime + “.Error.log”); // this goes on one line!!
    return logfileError;
    }
    }

    – then in your code behind you need to make a new instance of the errorFile class like so:

    errorFile errfile = new errorFile(); // make new instance of class
    logfileError = errfile.errorfile(); // access a function inside the class

    – then, whenever I want to write to the errorLog file i use the following code :

    using (StreamWriter errorLog = new StreamWriter(logfileError, false))
    {
    errorLog.WriteLine(“write something to the file, it could be text like this or a string”);
    }

    – I use the above to log when I get errors in my code and I log the error message to the file.

    Note: you will need to declare at the start of your code-behind the following for the StreamWriter to work :

    using System.IO; // needed for streamreader/writer

    Hope this helps someone.

    Trev.

  31. David says:

    Hi guys I hope this is not too late. But for windows forms (c#) you have to add the reference to System.Web. By default you may already have a reference to System.Web.Services but you need a reference to System.Web. And then include the Using System.Web (class library) in you declarations. Hope this helps.

Leave a reply to Varun Sareen Cancel reply