In my MVC app I want to get website's physical path on IIS server. My website's properties:
What I have tried is the following:
System.Diagnostics.Debug.WriteLine("MapPath: " + System.Web.Hosting.HostingEnvironment.MapPath("~/server/publish/"));
The above line is returning the path where my project was created:
MapPath: C:\ProjectVisualStudio\Reporting\CS\ServerSide\server\publish\
So, to get the physical path on IIS server, I was trying to obtain it with:
int iisNumber = 2;
using (ServerManager serverManager = new ServerManager())
{
var site = serverManager.Sites.Where(s => s.Id == iisNumber).SingleOrDefault();
var applicationRoot = site.Applications.Where(a => a.Path == "~/server/publish/").SingleOrDefault(); //here I get the exception
// var applicationRoot = site.Applications.SingleOrDefault();
var virtualRoot = applicationRoot.VirtualDirectories.Where(v => v.Path == "~/server/publish/").SingleOrDefault();
Console.WriteLine(virtualRoot.PhysicalPath);
System.Diagnostics.Debug.WriteLine("***************************************path IIS: " + virtualRoot.PhysicalPath + "***************************************");
}
But I get an exception
System.NullReferenceException: 'Object reference not set to an instance of an object.' site was null.
As you can see in the image, my site has the id = 2. Although running this:
System.Diagnostics.Debug.WriteLine($"Available sites: {string.Join(", ", serverManager.Sites.Select(s => s.Id))}");
is returnning:
Available sites: 1
Available sites: 1
What could I do to accomplish this task?