C# 如何使用 global.asax 中的 Server.MapPath()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/935940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use Server.MapPath() from global.asax?
提问by John Bubriski
I need to use Server.MapPath()
to combine some files path that I store in the web.config
.
我需要使用Server.MapPath()
来组合我存储在web.config
.
However, since Server.MapPath()
relies on the current HttpContext (I think), I am unable to do this. When trying to use the method, even though its "available", I get the following exception:
但是,由于Server.MapPath()
依赖于当前的 HttpContext(我认为),我无法做到这一点。尝试使用该方法时,即使它“可用”,我也会收到以下异常:
Server operation is not available in this context.
服务器操作在此上下文中不可用。
Is there another method that can map a web root relative directory such as ~/App_Data/
to the full physical path such as C:\inetpub\wwwroot\project\App_data\
?
是否有另一种方法可以将 Web 根相对目录映射~/App_Data/
到完整的物理路径,例如C:\inetpub\wwwroot\project\App_data\
?
采纳答案by Corbin March
You could try System.Web.Hosting.HostingEnvironment.MapPath().
你可以试试System.Web.Hosting.HostingEnvironment.MapPath()。
No HttpContext required.
不需要 HttpContext。
回答by VoltaicShock
You could try HttpContext.Current.Server.MapPath("/") - That's how I have referenced it before in classes.
您可以尝试 HttpContext.Current.Server.MapPath("/") - 这就是我之前在类中引用它的方式。
回答by tekBlues
When in Global.asax, use the contextobject:
在 Global.asax 中,使用上下文对象:
context.Server.mappath()
context.Server.mappath()
Context lets you access also the session collection, the request object, the response object. Very useful when you want to log errors, for example
上下文还允许您访问会话集合、请求对象、响应对象。例如,当您想记录错误时非常有用
回答by Kiran Banda
Use AppDomain.CurrentDomain.BaseDirectory
because Context
might return null !!
使用AppDomain.CurrentDomain.BaseDirectory
因为Context
可能返回 null !!