【问题标题】:ASPX - what is the path to my folder in web site?ASPX - 网站中我的文件夹的路径是什么?
【发布时间】:2011-07-16 14:29:54
【问题描述】:

我有一个网站项目 - ASPX,4.0。在其中我有一个文件夹,如:

bin\Xslt\Template.xslt

我想在我的类库中加载这个文件。在 web.config 中是:

 <configuration>
    <appSettings>
        <add key="Filepath" value=".\Xslt\Template.xslt" />
    </appSettings>
 </configuration>

但是,我的类库找不到它:

 mTransform = new XslCompiledTransform();
 mTransform.Load(ConfigurationManager.AppSettings["Filepath"]);

抛出:Could not find a part of the path 'C:\Xslt\Template.xslt'. 我知道这里有一个陷阱,但我不记得正确的方法了......

如何正确引用 aspx\bin\ 文件夹中的文件?

【问题讨论】:

    标签: c# asp.net configuration


    【解决方案1】:

    尝试将您的密钥更改为:

    <add key="Filepath" value="~/bin/Xslt/Template.xslt" />
    

    并将您的代码更改为:

    mTransform.Load(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["Filepath"]));
    

    【讨论】:

    • 由于这是在类库中,我想避免添加对 System.Web 的引用...
    【解决方案2】:

    使用Server.Mappath("~\xslt\template.xslt");

    【讨论】:

      【解决方案3】:

      尝试在您的网络配置中提供完整路径 例如,如果您的文件位于 C:\VSPROJECTS\bin\Xslt\Template.xslt

      然后在你的webconfig中写成

      【讨论】:

      • 绝对路径会随着部署到生产环境而改变,我想尽量减少对部署细节的依赖...
      【解决方案4】:

      我找到了方法(因为它在程序集中,我不想添加对 System.Web 的依赖):

      string codeBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
      string filepathRelative = ConfigurationManager.AppSettings["Filepath"];
      
      string fullFilepath = Path.Combine(codeBase, filepathRelative);
      

      谢谢

      编辑System.AppDomain.CurrentDomain.BaseDirectory 也可以解决问题...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-04
        • 2020-12-12
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多