Dom*_*ang 25 c# asp.net .net-assembly
我有一个像以下网站项目:
namespace Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lbResult.Text = PathTest.GetBasePath();
}
}
}
Run Code Online (Sandbox Code Playgroud)
该方法PathTest.GetBasePath()在另一个项目中定义,如:
namespace TestProject
{
public class PathTest
{
public static string GetBasePath()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么...\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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它File.config是在TestProject中创建的.现在AppDomain.CurrentDomain.BaseDirectory + m_filePath将returen ..\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\File.config),将由于过剩而抛出异常bin.
换句话说,在Web应用程序中,AppDomain.CurrentDomain.BaseDirectory是一个不同的路径,文件被复制到(缺少/bin),但在控制台应用程序中,它是相同的一个路径.
任何人都可以帮助我吗?
Pet*_*ter 35
根据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");
}
Run Code Online (Sandbox Code Playgroud)
另一个(未经测试)选项是使用:
public static string GetBasePath()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location;
}
Run Code Online (Sandbox Code Playgroud)
Paw*_*och 20
如果您想要一个适用于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
}
}
}
Run Code Online (Sandbox Code Playgroud)
以上解决方案代码段用于二进制文件位置
的AppDomain.CurrentDomain.BaseDirectory仍然是Web Apps的有效路径,它只是一个根文件夹,web.config并且Global.asax是一样的Server.MapPath(@"~\");
M4N*_*M4N 15
如果您使用AppDomain.CurrentDomain.SetupInformation.PrivateBinPath而不是BaseDirectory,那么您应该获得正确的路径.
| 归档时间: |
|
| 查看次数: |
52404 次 |
| 最近记录: |