Banshee
Banshee

Reputation: 15807

Get physical of the root of the website from inside a class?

Hi,

I have a mailhandler class in my MVC webapplication and needs to get a physical path to the mailTemplate file (a couple of folders down the root). How do I do this? Do I have to send in some kind of httpContext? My mailHandler is a singelton so there is no constructor for parameters :

public static EmailHandler Instance
{
    get {
        if (EmailHandler._emailHandler == null)
            EmailHandler._emailHandler = new EmailHandler();
        return EmailHandler._emailHandler; }
    set { EmailHandler._emailHandler = value; }
}

Any idea?

Upvotes: 1

Views: 115

Answers (3)

Eben Roux
Eben Roux

Reputation: 13256

You could always abstract your application configuration :)

public interface IApplicationConfiguration
{
    string EMailTemplateFolder { get; }
}

Then pass in an instance of a class implementing this interface into the relevant method. Passing in the instance to your EMailHandler is another option:

YourClassEMailHandlerContainer.Instance
    .InitializeWith(new ApplicationConfiguration())

Where ApplicationConfiguration : IApplicationConfiguration.

After this you just call your method.

YourClassEMailHandlerContainer.Instance.ParseTemplate(name)

Where internally:

var templateFile = 
    Path.Combine(applicationConfiguration.EMailTemplateFolder, name);

Hope that makes sense.

Upvotes: 1

longchiwen
longchiwen

Reputation: 822

  • you can store physical address of base folder in config file. Then do Path.Combine(baseFolder,templatefile) to get full path. This is preferred way, since it does not depend on having httpcontext accessible.
  • you can map that folder as virtual folder in IIS and then get physical path using Server.MapPath function

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062955

Personally, I would just tell it the base-path to use; then the same code can work in a number of environments, not just web. If you are web-bound, HttpContext.Current may help. If you want to pass it in, I would instead pass in the abstracted HttpContextBase, ala MVC.

But passing in a string of the base-path is a lot easier :)

Upvotes: 1

Related Questions