![](/img/trans.png)
[英]How to extract name/data from database and use it as my folder name which is created dynamically in asp.net c# using server.MapPath()?
[英]Using Server.MapPath in external C# Classes in ASP.NET
我试图获取C#类中某些文件的绝对路径。 Server.MapPath
当然适用于ASPX及其代码隐藏页面,但在另一个类文件中不存在。 我尝试了HostingEnvironment.MapPath()
,但是抱怨不允许相对虚拟路径。 有什么想法吗?
System.Web
已导入。
ServerUtility
类可用作HttpContext
的实例。 如果你所处的环境中你知道它将在ASP.Net管道中执行,你可以使用
HttpContext.Current.Server.MapPath()
您必须导入System.Web
。
你也可以用:
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/myfile.txt")
如果
var path = Server.MapPath("~/App_Data");
var fullpath = Path.Combine(path , "myfile.txt");
无法进入
你不能只是添加对System.Web
的引用,然后你可以使用Server.MapPath
?
编辑:现在我建议使用HostingEnvironment.MapPath
方法 :
它是System.Web
程序集中的静态方法,它将虚拟路径映射到服务器上的物理路径。 它不需要一个参考HttpContext
。
System.Reflection.Assembly.GetAssembly(type).Location
如果您要获取的文件是类型的装配位置。 但是,如果文件相对于程序集位置,则可以将其与System.IO
命名空间一起使用以获取文件的确切路径。
我也用它:
System.Web.HTTPContext.Current.Server.MapPath
这对我有帮助
//System.Web.HttpContext.Current.Server.MapPath //
FileStream fileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/File.txt"),
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
class test
{
public static void useServerPath(string path)
{
if (File.Exists(path)
{
\\...... do whatever you wabt
}
else
{
\\.....
}
}
现在当你从代码隐藏中调用方法时
例如 :
protected void BtAtualizacao_Click(object sender, EventArgs e)
{
string path = Server.MapPath("Folder") + "\\anifile.txt";
test.useServerPath(path);
}
通过这种方式你的代码很简单,一个方法你可以为每个调用使用多个路径:)
无论您是否在ASP.NET的上下文中运行,您都应该能够使用HostingEnvironment.ApplicationPhysicalPath
server.mappath(“”)将在aspx页面上工作,如果你想从类文件中获取绝对路径,你必须使用这个 -
HttpContext.Current.Server.MapPath("~/EmailLogic/RegistrationTemplate.html")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.