简体   繁体   中英

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.

在此处输入图像描述

And I need programmatically to set the physical path to this configuration file in this getter to configure NHibernate (the line with 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?

In the properties window for the file, set the "Copy to Output Directory" to "Copy if newer". It should then be found by the Configure method without adding a path (just the filename).

Edit: To get the full path at runtime, you can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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