[英]Why is AppDomain.CurrentDomain.BaseDirectory targeting bin catelog in console application?
[英]Why AppDomain.CurrentDomain.BaseDirectory not contains "bin" in asp.net app?
我有一个网络项目,如:
namespace Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lbResult.Text = PathTest.GetBasePath();
}
}
}
PathTest.GetBasePath()
方法在另一个项目中定义,如:
namespace TestProject
{
public class PathTest
{
public static string GetBasePath()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
为什么它显示...\\Web\\
而 TestProject 程序集编译到bin
文件夹中(换句话说,它应该在我的想法中显示...\\Web\\bin
)。
现在,如果我将方法修改为:
namespace TestProject
{
public class FileReader
{
private const string m_filePath = @"\File.config";
public static string Read()
{
FileStream fs = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + m_filePath,FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs);
return reader.ReadToEnd();
}
}
}
File.config
在 TestProject 中创建。 现在AppDomain.CurrentDomain.BaseDirectory + m_filePath
将返回..\\Web\\File.config
(实际上是将文件复制到..\\Web\\bin\\File.config
),会抛出异常。
你可以说我应该将m_filePath
修改为@"\\bin\\File.config"
。 但是,如果我在您建议的控制台应用程序中使用此方法, AppDomain.CurrentDomain.BaseDirectory + m_filePath
将返回..\\Console\\bin\\Debug\\bin\\File.config
(实际上该文件已..\\Console\\bin\\Debug\\bin\\File.config
到.\\Console\\bin\\Debug\\File.config
),因为bin
多余会抛出异常。
换句话说,在 Web 应用程序中, AppDomain.CurrentDomain.BaseDirectory
是将文件复制到的不同路径(缺少/bin
),但在控制台应用程序中它是相同的路径。
任何人都可以帮助我吗?
根据 MSDN,应用程序域“代表应用程序域,它是应用程序执行的隔离环境。” 当您考虑 ASP.Net 应用程序时,应用程序所在的根目录不是 bin 文件夹。 在您的 bin 文件夹中没有文件是完全可能的,并且在某些情况下是合理的,并且可能根本没有 bin 文件夹。 由于 AppDomain.CurrentDomain 指的是同一个对象,无论您是从后面的代码还是从 bin 文件夹中的 dll 调用代码,您最终都会得到网站的根路径。
当我编写了在 asp.net 和 windows 应用程序下运行的代码时,通常我会创建一个如下所示的属性:
public static string GetBasePath()
{
if(System.Web.HttpContext.Current == null) return AppDomain.CurrentDomain.BaseDirectory;
else return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin");
}
另一个(未经测试的)选项是使用:
public static string GetBasePath()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location;
}
如果您想要一个适用于 WinForms 和 Web Apps 的解决方案
public string ApplicationPath
{
get
{
if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))
{
return AppDomain.CurrentDomain.BaseDirectory; //exe folder for WinForms, Consoles, Windows Services
}
else
{
return AppDomain.CurrentDomain.RelativeSearchPath; //bin folder for Web Apps
}
}
}
以上解决方案代码片段适用于二进制文件位置
AppDomain.CurrentDomain.BaseDirectory
仍然是 Web Apps 的有效路径,它只是web.config
和Global.asax
所在的根文件夹,与Server.MapPath(@"~\\");
如果您使用AppDomain.CurrentDomain.SetupInformation.PrivateBinPath
而不是BaseDirectory
,那么您应该获得正确的路径。
当 ASP.net 构建您的站点时,它会在其特殊位置为它们输出构建程序集。 所以以这种方式获得路径很奇怪。
对于 asp.net 托管应用程序,您可以使用:
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.