为什么AppDomain.CurrentDomain.BaseDirectory在asp.net应用程序中不包含“bin”?
我有一个像以下网站项目:
namespace Web { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lbResult.Text = PathTest.GetBasePath(); } } }
PathTest.GetBasePath()
方法在另一个Project中定义,如:
namespace TestProject { public class PathTest { public static string GetBasePath() { return AppDomain.CurrentDomain.BaseDirectory; } } }
为什么它显示...Web
而TestProject程序集被编译成bin
文件夹(换句话说,它应该在我的思想中显示...Webbin
)。
如果我修改了方法,我现在遇到了麻烦:
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
将返回..WebFile.config
(实际上该文件被复制到..WebbinFile.config
),将抛出exception。
你可以说我应该将m_filePath
修改为@"binFile.config"
。 但是,如果我在建议的Console应用程序中使用此方法, AppDomain.CurrentDomain.BaseDirectory + m_filePath
将返回..ConsolebinDebugbinFile.config
(实际上该文件已..ConsolebinDebugbinFile.config
到.ConsolebinDebugFile.config
),由于剩余bin
而抛出exception。
换句话说,在Web应用程序中, AppDomain.CurrentDomain.BaseDirectory
是一个不同的路径,其中文件被复制到(缺少/bin
),但在控制台应用程序中它是相同的一个路径。
任何人都可以帮助我吗?
根据MSDN,App Domain“表示应用程序域,它是应用程序执行的隔离环境。” 当您考虑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; }
如果您使用AppDomain.CurrentDomain.SetupInformation.PrivateBinPath
而不是BaseDirectory
,那么您应该获得正确的路径。
如果您想要一个适用于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(@"~");
当ASP.net构建您的站点时,它会在其特殊位置输出构建程序集。 因此以这种方式获得路径是很奇怪的。
对于asp.net托管的应用程序,您可以使用:
上述就是C#学习教程:为什么AppDomain.CurrentDomain.BaseDirectory在asp.net应用程序中不包含“bin”?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1023111.html