简体   繁体   English

如何以编程方式设置此 xml 文件的物理路径?

[英]How can I set the physical path of this xml file programmatically?

I have my hibernate.cfg.xml congif file placed in PersistenceManager project as you see in the picture.如图所示,我将 hibernate.cfg.xml congif 文件放在 PersistenceManager 项目中。

在此处输入图像描述

And I need programmatically to set the physical path to this configuration file in this getter to configure NHibernate (the line with cfg.Configure ):我需要以编程方式在此 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;
        }
    }
}

How can I do it safely just by typing the string "hibernate.cfg.xml" and letting the C# to generate the rest of the physical path?我怎样才能通过键入字符串“hibernate.cfg.xml”并让 C# 生成物理路径的 rest 来安全地做到这一点?

In the properties window for the file, set the "Copy to Output Directory" to "Copy if newer".在文件的属性 window 中,将“复制到 Output 目录”设置为“如果较新则复制”。 It should then be found by the Configure method without adding a path (just the filename).然后应该通过Configure方法找到它,而无需添加路径(只是文件名)。

Edit: To get the full path at runtime, you can try this:编辑:要在运行时获取完整路径,您可以尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM