Get IIS default installation directory - c#

From what I can tell all ASP.NET web applications are placed into C:\inetpub folder by default. But is there any way to retrieve this folder in a C# code? Or do I just hard code it?
PS. I need this as a default folder for my C# program that installs my web application.

The following is limited to my experience so . . . YMMV
I do not believe that there is a true default location.
IIS will host a site in any folder that IIS has access permissions for. To determine what folder that might be, you can query the existing site list.
BUT
All is not lost. You can figure out where those sites are!
In a new IIS installation you can locate the directory of the "Default Site" created during the IIS installation.
Just keep in mind that there are no guarentees that the site will remain there. Personally, I delete the Default Site as soon as I start to configure IIS.
In IIS 7+
Site locations can be found in an XML file under IIS's configuration folder.
%systemroot%\System32\inetsrv\config\
In the XML file applicationHost.config see
The XML Node path is:
/configuration/system.applicationHost/sites/
From there you can iterate through each child node to see the various folder locations. For example, the default site will probably be listed as:
child node: site name="Default Web Site" id="1"
The .Net Way
Another trick would be to query IIS directly via .Net.
Here is the API documentation
Here are some methods to keep in your back pocket:
private static Site GetSite(string siteName)
{
Site site = (from s in (new ServerManager().Sites) where s.Name == siteName select s).FirstOrDefault();
if (site == null)
throw new Exception("The Web Site Name \"" + siteName + "\" could not be found in IIS!");
return site;
}
private static ApplicationCollection GetApplications(Site site)
{
//HttpContext.Current.Trace.Warn("Site ID3: " + site + "/n");
ApplicationCollection appColl = site.Applications;
return appColl;
}
private static String GetHostName(Site site)
{
BindingCollection bindings = site.Bindings;
String bind = null;
foreach (Binding binding in bindings)
if (binding.Host != null)
return binding.ToString();
return bind;
}
Update!
While I can't guarantee that this location will remain after install, you can also query the registry:
Check out HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\InetStp\pathWWWRoot\

I'm posting this as a seperate answer as its a completely different solution:
Do not worry where other apps are installed!
Use Web Deploy (and if you're getting creative with Web Publish, you can even set specific folder permissions)
If you need to do this pragmatically/have no access to those nifty tools...
Choose a location and set permissions on the folder to ensure that IIS is able to access it.
Then using the IIS API's register your new site.
Oh and you'll need to check those app pool permissions too

Related

Can't see path to another server in ASP.NET MVC

I have an internal ASP.NET MVC site that needs to read an Excel file. The file is on a different server from the one that ASP.NET MVC is running on and in order to prevent access problems I'm trying to copy it to the ASP.NET MVC server.
It works OK on my dev machine but when it is deployed to the server it can't see the path.
This is the chopped down code from the model (C#):
string fPath = HttpContext.Current.Server.MapPath(#"/virtualdir");
string fName = fPath + "test.xlsm";
if (System.IO.File.Exists(fName))
{
// Copy the file and do what's necessary
}
else
{
if (!Directory.Exists(fPath))
throw new Exception($"Directory not found: {fPath} ");
else
throw new Exception($"File not found: {fName } ");
}
The error I'm getting is
Directory not found:
followed by the path.
The path in the error is correct - I've copied and pasted it into explorer and it resolves OK.
I've tried using the full UNC path, a mapped network drive and a virtual directory (as in the code above). Where required these were given network admin rights (to test only!) but still nothing has worked.
The internal website is using pass through authentication but I've used specific credentials with full admin rights for the virtual directory, and the virtual dir in IIS expands OK to the required folder.
I've also tried giving the application pool (which runs in Integrated mode) full network admin rights.
I'm kind of hoping I've just overlooked something simple and this isn't a 'security feature'.
I found this question copy files between servers asp.net mvc but the answer was to use FTP and I don't want to go down that route if I can avoid it.
Any assistance will be much appreciated.
First, To be on the safe side that your directory is building correctly, I would use the Path.Combine.
string fName = Path.Combine(fPath, "test.xlsm")
Second, I would check the following post and try some things there as it seems to be a similar issue.
Directory.Exists not working for a network path
If you are still not able to see the directory, there is a good chance the user does not have access to that network path. Likely what happened is the app pool running your application has access to the directory on the server. The production box likely doesn't have that same access. You would have to get with the network engineer to get that resolved.
Alternatively, you could write a Powershell script to run as a user who has access to both the production and the development server to copy the file over to the production server if that is your ultimate goal and your server administrators could schedule it for you if that is allowed in your environment.

Environment.ExpandEnvironmentVariables returns unexpected path in IIS

var filename = Environment.ExpandEnvironmentVariables(#"%LOCALAPPDATA%\Dropbox\info.json");
When I run it in vs I get the path I need which is
C:\Users\User-pc\AppData\Local\Dropbox\info.json
when published to IIS I get
C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Dropbox\info.json
This is because IIS is not running under your user account. It is running under a system account. C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\ is the correct path for the IIS account.
You could set the user account on the IIS app pool to be your user (not great for secuirty, https://technet.microsoft.com/en-us/library/cc771170(v=ws.10).aspx), or you could pass the correct path in another way (web.config maybe)?
%LOCALAPPDATA% is a user specific folder.
IIS doesn't use the same user as you when you run from VS.
In my opinion there are 2 solutions :
- Change the folder of this file to something more usual (Your web site folder, or something like D:\Dropbox\info.json)
- Change the user IIS uses, but that's really not a good option

Creating a folder on the desktop

I want to create a folder on my current user's desktop folder, however; I keep getting an access denied message. I have full write permissions under my profile in IIS.
string activeDir = #"C:\Users\dmm\Desktop\";
string newPath = System.IO.Path.Combine(activeDir, "mySubDir");
System.IO.Directory.CreateDirectory(newPath);
Any help would be appreciated.
Try using the built in objects to get the desktop path, and let .NET also handle the path building for the new folder. You will also want to check if the directory exists first.
string newFolder = "abcd1234";
string path = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
newFolder
);
if(!System.IO.Directory.Exists(path)) {
try {
System.IO.Directory.CreateDirectory(path);
} catch (IOException ie) {
Console.WriteLine("IO Error: " + ie.Message);
} catch (Exception e) {
Console.WriteLine("General Error: " + e.Message);
}
}
When you deploy an application on IIS by default it is executed with ApplicationPoolIdentity. Which is virtual user created and named as IIS AppPool\YourPoolName If this virtual user does not have write access to your desktop. You get that exception.
You have two options.
Give ApplicationPoolIdentity user write access to Desktop directory.
goto Desktop folder and add user IIS AppPool\YourPoolName with write access :
Change pool Identity to user which has write access to directory.
Go
IIS->Application Pools -> Your AppPool ->Advanced Settings -> Identity
->
Select Custom Account and click set button. and there you enter your windows user credentials.
I would recommend first option.
There are many to consider here, first of them being that your application is an ASP.NET application, and every current user will be different. If your application — just assume — runs correctly on your machine, it will never run on hosting environment because they do not grant write permissions to special folders and user accounts.
That said, you need to work in physical paths in order to create your directories.
var path = "C:\\Users\\afzaa\\Desktop\\";
var folder = Path.Combine(path, "folder");
Directory.CreateDirectory(folder);
The result of the above code is,
As you can see, the code properly works and has no issue at all in execution.
There are few things to note:
Your application has read/write permissions. Check IIS for that.
Your code can actually lookup the path you are trying to access. That applies to any folder inside Desktop too, a sub folder may have special permissions applied.
Do not do this, write the content online in your hosting domain. Users have different accounts and structures for folders and thus this will not work — Desktop path is different.
If you want to users to download the file, simply stream the file down and let them save it where they want to.
https://forums.asp.net/t/1807775.aspx?Create+e+New+Folder+Access+Denied+
https://answers.microsoft.com/en-us/windows/forum/windows_xp-files/unable-to-create-the-folder-new-folder-access-is/ac318218-a7b2-4ee2-b301-2ad91856050b
.NET MVC Access denied when trying to create Directory
If you ran your logic from an IIS application, you should use Server.MapPath:
System.IO.Directory.CreateDirectory(Server.MapPath(newPath));

Set write permission on folder create

Hi I have been trying to properly configure IIS 6 to give write permisiosn for about 2 days now and I can't seem to find any good resource on this.I am a bit new to ASP.NET and until now I never had to work with IIS.
What I am trying to do is upload a file to the server.Each user on the server will have his own special folder witch will be created automaticly via C#.Now when I try to upload the file I get this error:
Access to the path 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru' is denied
This is my code for creating the folder for each user and saving the file:
private void addImageToApp()
{
string path = "~/Images/avatar/userAvatars/" + User.Identity.Name;
createPath(path);
if( Directory.Exists(HostingEnvironment.MapPath(path)))
{
try {
UploadImage.SaveAs(HostingEnvironment.MapPath(path));
MultiViewIndex.ActiveViewIndex = 0;
}catch(Exception ex)
{
AvatarDetails.Text = ex.Message;
}
}
}
private void createPath(string path)
{
string activeDir = HostingEnvironment.MapPath("~/Images/avatar/userAvatars");
if( !Directory.Exists(Server.MapPath(path)) )
{
string newPath = Path.Combine(activeDir, User.Identity.Name);
Directory.CreateDirectory(newPath);
}
}
All I could find on the internet is that I have to add write permision via folder/properties/security/... while that is all good and fine I can not do this for each folder.
Up to this point I am not really sure that IIS is the one I need to configure I am a bit lost at this.
What do I have to do to give folders write permisions automaticly on folder create?
And if anyone has a good article or tutorial that shows how to do this please share it with me all the info I could find were very basic.
EDIT
I have added the network service account to the Images folder with full permision and have set the application's pool Identity to NetworkService but I still get the same error
EDIT
I have messed around with SQL-SERVER for the last couple of days in order to make this work so I might have missconfigured something form what I understand NETWORK SERVICE is stored in SQL-SERVER master.db database.I seem to be having two network service logins may this be the problem?I remember when I first checked it I had none now I have two:
Simply, when your asp.net application running you can open Task Manager and find process w3wp.
W3wp process like any other has user identity (by default - application pool identity - DefaultAppPool(like application pool name)).
And if it so, you should add write permissions for user named DefaultAppPool. To do it you should open security tab in folder's properties window, then change->add and type IIS AppPool/DefaultAppPool and choose local machine.
This post should help you!
This has nothing to do with IIS, brother. All you need to do is, open your IIS. Go to Application Pool. Right click on the Application Pool your website is running with. Select "Advanced Settings" and see the entry made against IDENTITY. Change it to use NetworkService. This will mean that you will be running your website under NETWORK SERVICE account now on.
Now right-click your root images folder, i.e., "Images". Select PROPERTIES. Select SECURITY. Add user NETWORK SERVICE, and give it FULL RIGHTS permissions on the folder.
Now whenever you create a folder and file under this "Images" folder through your code, it will automatically inherit permissions from its parent and you will allow you to do whatever you want (Add/Delete).
I hope this answers your question. If yes, then please mark it as "answered".

Checking whether a folder exists under an IIS application using C#

I'm working on a web based deployment tool in C# which deploys applications remotely on IIS 7.
I've reached a point where where I'm able to deploy an application. Now I need to see if the application that is deployed has a a certain directory before attempting to set permissions on it (Since the tool would deploy different applications which may or may not have that folder).
There are two approaches that I took:
I've checked for classes that I can use under the ServerManager namespace. I can get a handle on an application deployed under a certain application pool using:
var iis = ServerManager.OpenRemote("serverName")
var iisApplication = iis.Sites[site].Applications["appName"];.
Now I can get the virtual directories under the application using :
var virtualDirectory = iisApplication.VirtualDirectories;
But then I'm not able to see a whole lot of folders which are under that virtual directory. For axample, my application is deployed as test and iisApplication.VirtualDirectories.First() gives me /test. I was want to be able to /test/_ApplicationLogs which is the directory I want to set permissions on.
My next approach was to use DirectoryEntry. Here, I'm not able to figure out the metabase path to use for my application. Is there a standard metabase path used for IIS 7?
For an application called test deployed locally, what would the metabase path be? And would I be able to get all the children so that I can use DirectoryEntry.Exists?
For now, I have a workaround. I can use the WhatIf (set it true) property under DeploymentSyncOptions, do a sync and then check if an object got added. If it did, the directory does not exist. Code :
var syncOptions = new DeploymentSyncOptions();
syncOptions.WhatIf = true;
using (deploymentObject)
{
var result = deploymentObject.SyncTo(
DeploymentWellKnownProvider.SetAcl,
"Default Web Site/path_to_folder",
destinationBaseOptions,
syncOptions);
if (result.ObjectsAdded != 0)
{
syncOptions.WhatIf = false;
deploymentObject.SyncTo(DeploymentWellKnownProvider.SetAcl,
"Default Web Site/path_to_folder",
destinationBaseOptions,
syncOptions);
}
}

Categories