我应该怎么做才能让Server.MapPath
正常工作?
我已经使用了using System.Web;
还需要什么?当我输入Server
时,没有快速结果选项(智能感知)出现。
有什么帮助吗?
我应该怎么做才能让Server.MapPath
正常工作?
我已经使用了using System.Web;
还需要什么?当我输入Server
时,没有快速结果选项(智能感知)出现。
有什么帮助吗?
你可以尝试使用这个
System.Web.HttpContext.Current.Server.MapPath(path);
或者使用HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
HostingEnvironment.MapPath("/MyFolder")
返回 c:\inetpub\wwwroot\。需要添加 HostingEnvironment.MapPath("~/MyFolder")
以返回正确的路径。 - sky91您的项目需要引用程序集 System.Web.dll
。 Server是类型为 HttpServerUtility
的对象。示例:
HttpContext.Current.Server.MapPath(path);
System.Web.HttpContext.Current.Server.MapPath("~/")
如果我们从一个线程中调用它,将会返回 null。
因此,请尝试使用
System.Web.Hosting.HostingEnvironment.MapPath("~/")
System.web
的引用,如果您没有,请在 References 文件夹中完成。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
添加为您的项目引用。
我曾经遇到过同样的问题,我想这可能会对某些人有所帮助。正如这个问题的原始发布者所问:
我必须做什么才能让Server.MapPath工作?
我已经使用了System.Web;
我们编写的类应该实现System.Web.UI.Page
例如,假设我们的类名是MyClass
public class MyClass: System.Web.UI.Page
{
// Code runs here
}
我知道这篇文章已经有几年了,但我的做法是在你的类的顶部添加这行代码,这样你仍然可以使用 Server.MapPath。
Dim Server = HttpContext.Current.Server
或者你可以创建一个函数
Public Function MapPath(sPath as String)
return HttpContext.Current.Server.MapPath(sPath)
End Function
我一直致力于让事情变得更简单。为了以防万一再次遇到这种情况,我还将它添加到我的实用程序类中。