Click here to Skip to main content
15,883,705 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my MVC app I want to get website's physical path on IIS server. This old post is about it, but I'm using a newer version of IIS (10.0.19041.1). Is there another way of accomplishing this task? I was trying the accepted solution from the above mentioned post, but it throws me an exception: System.NullReferenceException: 'Object reference not set to an instance of an object.' site was null..

What I have tried:

using Microsoft.Web.Administration;
//...

    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 == "/").SingleOrDefault(); //here I get the exception
            var virtualRoot = applicationRoot.VirtualDirectories.Where(v => v.Path == "/").SingleOrDefault();
            Console.WriteLine(virtualRoot.PhysicalPath);
            System.Diagnostics.Debug.WriteLine("***************************************path to IIS website: " + virtualRoot.PhysicalPath + "***************************************");
        }
Posted
Updated 18-May-22 0:49am

1 solution

If site is null, then you do not have a site configured with an ID of 2.

Open IIS Manager, select the Sites node, and check the ID column to see the IDs of the site(s) you have configured.
 
Share this answer
 
Comments
DrgIonuţ 19-May-22 3:13am    
Thanks for replying, Richard! I have checked and the id of my website is 2. What else could I do?
Richard Deeming 19-May-22 5:33am    
Try:
Console.WriteLine("Available sites: {0}", string.Join(", ", serverManager.Sites.Select(s => s.Id)));

Check which site IDs are being returned by the ServerManager.
DrgIonuţ 19-May-22 7:43am    
Running your code, I get: 1: Available sites: {0}
This means that I get only the DefaultSite which in my case has the ID = 1?
Richard Deeming 19-May-22 8:03am    
That output suggests the placeholder hasn't been replaced. It should look more like:
Available sites: 1
DrgIonuţ 19-May-22 8:12am    
The question is which site is available? DefaultSite or my site?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900