How to verify network files and folders from IIS applications - c#

We have an Intranet web application (ASP.NET 4.5) on SERVER-B. It's on the same domain as SERVER-A. How can I check if a file exists on SERVER-A from the Intranet application? I tried using File.Exits/Directory.Exis, FileWebRequest, cannot get it to work. Is there an IIS setting to allow?
Note: I can browse the files on Server-A from Server-B using file explorer.
Note: HttpWebRequest 'does' work for finding files on our external website but that method does not work for our intranet to network.
Method A (result is always false)
File.Exists("\\xyz-123\Shipping\State\ca.doc")
Directory.Exists("\\xyz-123\Shipping\State")
Method B (result is always false and doesn't return an error)
'url = "file://xyz-123/Shipping/State/ca.doc"
Private Function FileExist(url As String) As Boolean
Dim response As WebResponse = Nothing
Try
Dim request = DirectCast(WebRequest.Create(url), FileWebRequest)
request.Method = "HEAD"
response = DirectCast(request.GetResponse(), WebResponse)
FileExist = True
Catch ex As Exception
Finally
If response IsNot Nothing Then response.Close()
End Try
End Function

The Method A will work if you share the \\xyz-123\Shipping\State folder with the user running the code.

Almost certainly your problem is permissions related. Your IIS website runs as an "IIS Application" belonging to an Application Pool in IIS. That Application Pool has a windows login associated with it. That login needs to have permission to acces the files on the second machine.
To fix the problem, look at the application pool setup in IIS and find out what user the application pool is running under, and change the permissions on the file share to allow them access. To debug this you can try assigning your own credentials to the IIS Application Pool your website is running under and you might find it works, becasue you personally do have rights to access the files.

Related

Unable to write IIS hosted application to a shared folder in Ubuntu but no problem with IISExpress

I have a shared folder (assets) in the Ubuntu machine and ASP.NET MVC application in a Windows machine. Both machines are in the same network and I have to save files in the shared folder in Ubuntu from the MVC application. When I run the application in IISExpress, the application saves the files without any error. But when I host the application in IIS, it gives me an error.
The specified server cannot perform the requested operation.
Here is the code I am using to save the files.
try
{
string sourceFile = #"D:\myfile.pdf";
string destinationPath = #"\\ubuntu\assets/";
byte[] fileBytes = System.IO.File.ReadAllBytes(sourceFile);
System.IO.File.WriteAllBytes(destinationPath + Guid.NewGuid().ToString() + ".pdf", fileBytes);
}
catch (Exception ex)
{
}
I played with Identity in Application Pool in IIS to LocalSystem, NetworkService. Any thoughts on how to achieve this goal?
One way I achieve this is as below:
Go to the particular Application Pools and click on Advanced Settings.
Click on Identity and click on Custom account and click on Set…
Put window's current login User name, Password and Confirm password.
Click OK and recycle the Application pool by right-clicking and clicking on Recycle.
I don't know if it is the right way to doing.

IIS AppPool identity denied access to move file

I have this exact (best as I can see) scenario on a test server and it works as expected.
IIS Application needs to move a file on the D drive from one sub folder to another subfolder
D:\supportfiles\new (file is here)
D:\supportfiles\backup (file needs to be moved here)
I gave the app pool modify access to the top level folder, D:\supportfiles
This works as expected on my test server, but not on a different server that I published to. The app pool has permissions, or at least it appears it does.
I get this error
System.UnauthorizedAccessException: Access to the path is denied.
File.Move(OldPath + FileName, NewPath + FileName);
Go to advance settings of your application apppool and set it to LocalSystem instead of apppool identity. Or setup a new user specially for using in apppool.
It's usually caused for some os hardening issues on product servers.
it happened to me. console application for sure. start as an administrator and try again?

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

Access to the path 'Global\{xxx}_YYY-YYY:13552' is denied. Hangfire?

As the title says I encounter a "Access to the path" error in my MVC web application. The sites application pool is DefaultAppPool with identity Network Service. I have set Full Control to the Network Service user with no luck, I then tried to give Everyone full control but it still does not work. I'm running another application from the same folder (C:\Users\YYY\Documents\Visual Studio 2015\Projects) and it works without a problem.
The file that fails contains the method that starts Hangfire. Could this have something to do with it?
I'm running Windows 10 Pro with IIS 10.0.
public void Start()
{
lock (_lockObject)
{
if (_started) return;
_started = true;
HostingEnvironment.RegisterObject(this);
GlobalConfiguration.Configuration
.UseSqlServerStorage("connection string");
// Specify other options here
_backgroundJobServer = new BackgroundJobServer();
}
}
http://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html
Current permissions for
C:\Users\YYY\Documents\Visual Studio 2015\Project
Server Error in '/' Application.
Access to the path
'Global{4deecd4f-19f6-426b-xxxx-xxxxxxxxxxxx}_YYY-YYY:13552' is
denied.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the
path
'Global{4deecd4f-19f6-426b-xxxx-xxxxxxxxxxxx}_YYY-YYY:13552' is
denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
the configured application pool identity on IIS 7.5) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in File
Explorer, choose "Properties" and select the Security tab. Click "Add"
to add the appropriate user or group. Highlight the ASP.NET account,
and check the boxes for the desired access.
Source Error:
Line 36: _backgroundJobServer = new BackgroundJobServer();
Found the problem, I had two websites with Hangfire running on the same application pool. When I created a new application pool for each website everything started working.
It seems as both instances of Hangfire when running on the same application pool tried to communicate through the same port and because of this the application that got started first was the only one to be working. The reason they were on the same application pool to start with was pure laziness, I only created a virtual directory from within Visual Studio at my local IIS to run the project.

Executing batch file from C# Permission issue

I have a batch file to execute a VB script. While executing the batch file by double clicking will work, But when I have done the same with C# its working on my local environment but not in the staging server (windows server 2008r2), Is there any permission level i need to apply for this execution. From the staging server I can double click and execute the batch file...
I have logged in to the server with Administrator account and browsed the application as localhost.
Is there anything I'm missing on the execution of batch file from C#,
I don't think there is any problem with my C# code as its working fine on my local environment, anyway following is my C# code,
if (File.Exists(FileName*))
{
System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo(FileName);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = FileName;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
}
else
{
lblMsg.Text = "Sorry unable to process you request";
}
*FileName is the path to batch file. Also I have set full permission to the folders that containg both batch file and vbs files.
For this to work your app pool needs to be run as a user who has access to the batch file.
Check how to change your app pool identity for IIS 7 or IIS 6.
To expand on what Kartheek said:
In IIS 7 application pools run as a app pool account, IISAPPPOOL\AppPoolName
In IIS 6 application pools run as Network Service
In either case, these accounts don't have any access a user's documents folder and (by default) can only read from common data stores.
Generally you want to keep the app pool account because it helps segregate the data -- so what I would do is just make sure you grant read+execute permissions on the bat file you need for the app pool account. You'll also need proper permissions on any filles/folders the bat needs to read/write from.
You do not need to change anything in your app to correct this problem, unless you want to IIS app to masquerade around as the user who is actually sitting at the website (it only really works if you use some form of authentication.) Generally this a bad idea anyway -- so it's best to just adjust the permissions.
As a general rule of thumb, when working on a web server you want to keep the permissions/execution levels as low/restrictive as possible.

Categories