简体   繁体   中英

Cannot use Server.MapPath

What I must do to make Server.MapPath work?
I have using System.Web;

what else? When I type Server there is no quick result option (intelli-sense) for Server .

Any help?

you can try using this

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

or use HostingEnvironment.MapPath

    System.Web.Hosting.HostingEnvironment.MapPath(path);

Your project needs to reference assembly System.Web.dll . Server is an object of type HttpServerUtility . Example:

HttpContext.Current.Server.MapPath(path);

System.Web.HttpContext.Current.Server.MapPath("~/") gives null if we call it from a thread.

So, Try to use

System.Web.Hosting.HostingEnvironment.MapPath("~/")

Firt add a reference to System.web , if you don't have. Do that in the References folder.

You can then use Hosting.HostingEnvironment.MapPath(path);

bool IsExist = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
if (!IsExist)
    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/UploadedFiles/"));

StreamWriter textWriter = File.CreateText(Path.Combine(HttpContext.Current.Server.MapPath("/UploadedFiles/") + "FileName.csv"));
var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);
csvWriter.WriteRecords(classVM);

尝试添加System.Web作为对您的项目的引用。

您需要添加对System.Web引用( System.Web引用

I know this post is a few years old, but what I do is add this line to the top of your class and you will still be able to user Server.MapPath

Dim Server = HttpContext.Current.Server

or u can make a function

Public Function MapPath(sPath as String)
    return HttpContext.Current.Server.MapPath(sPath)
End Function

I am all about making things easier. I have also added it to my Utilities class just in case i run into this again.

I faced the same problem and I guess this might help someone. As the Original Poster of this question asked

What I must do to make Server.MapPath work?
I have using System.Web;

The class which we had written should implement System.Web.UI.Page

Say for example, our classname is MyClass

public class MyClass: System.Web.UI.Page
{
// Code runs here 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM