【问题标题】:How can I set the physical path of this xml file programmatically?如何以编程方式设置此 xml 文件的物理路径?
【发布时间】:2011-07-16 09:39:29
【问题描述】:

如图所示,我将 hibernate.cfg.xml congif 文件放置在 PersistenceManager 项目中。

我需要以编程方式在此 getter 中设置此配置文件的物理路径以配置 NHibernate(带有 cfg.Configure 的行):

public class SessionService
{
    private static ISessionFactory _sessionFactory = null;
    public static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
            {
                Configuration cfg = new Configuration();
                string fullPath = (new SessionService()).GetType().Assembly.Location;

                cfg.Configure(@"the working path to hibernate.cfg.xml");

                //I will Add Mapping directives here

                _sessionFactory = cfg.BuildSessionFactory();
            }

            return _sessionFactory;
        }
    }
}

如何仅通过键入字符串“hibernate.cfg.xml”并让 C# 生成物理路径的其余部分来安全地执行此操作?

【问题讨论】:

    标签: c# .net xml path


    【解决方案1】:

    在文件的属性窗口中,将“复制到输出目录”设置为“如果较新则复制”。然后应该通过Configure 方法找到它,而无需添加路径(只是文件名)。

    编辑:要在运行时获取完整路径,您可以试试这个:

    cfg.Configure(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"hibernate.cfg.xml"));
    

    【讨论】:

    • 只要应用程序的工作目录设置为它自己的目录,这应该可以工作。情况可能并非如此(例如,作为服务运行或从自动启动时),因此添加可执行文件的路径不会造成损害。
    • @Mario:但我怎样才能以编程方式做到这一点?
    • 要获取应用程序的路径,只需评估 'Path.GetDirectoryName(Application.ExecutablePath)'。
    • Mario 的建议也不错,但如果您的代码库中还没有 System.Windows.Forms 程序集,则需要添加对它的引用。
    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2016-09-25
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多