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

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.

Related

Unable to determine if a file is on a web server because the various methods of determining the directory do not work

I am developing an application in asp.net, vs2015 using c# and the development environment is a Win10Pro machine. I can use any of the various methods to obtain the working directory and see if a particular file exists on the dev pc, but not on the Web Server. I have tried the methods laid out on:
Get current application physical path within Application_Start
All work on the Dev PC, but when used on the Web Server it will not return the working directory. The Server is a 2016 Data server using IIS10. The issue is that the web site I am putting together work fine, except to display GrapeCity ActiveReports reports AR15. The web page containing their web viewer opens just fine and is looking for a report file (MyReport.rdlx). The global.aspx file is pointing to the root directory but when the web viewer opens up, it says File Not Found. I have absolutely no idea and tech support is not sure. Is this an IIS issue that is preventing the code to locate and verify the file is there? Any direction would be much appreciated. This has been very frustrating and time consuming.
AppDomain.CurrentDomain.BaseDirectory does not work, HttpRuntime.AppDomainAppPath does not as well as all the others. The request comes back blank.
string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() +"SPU01_Dates.rdlx";
if (File.Exists(filename))
{
Response.Write("YES");
}
else
{
Response.Write("NO");
Response.Write("</br");
Response.Write(filename);
}
All this just returns nothing.
Thanks.
Try this code
if (File.Exists(Server.MapPath(filename)))
Check if a file exists on the server
In my test, it returned YES and worked well. Did you put "SPU01_Dates.rdlx" file in root folder?
In the development environment, it returned YES, and when I deployed it to IIS, it returned NO. I found that during the deployment process, the rdlx file was not deployed with the project, so I recreated one in the deployed folder, and it returned YES.
The test proves that AppDomain.CurrentDomain.BaseDirectory is the most accurate way to get the file path. When you test this code in IIS, does it return NO or empty? Returning empty means that this piece of code has not been executed.

Application can find 'Downloads' folder when debugging but not on IIS

I have an application that allows the user to upload a file (saving it to in a folder located in the wwwroot of the ASPNETCORE application). From here they can make edits to it and then they can choose to export the file as a csv/ xml/ xlsx which downloads the file to the user's 'downloads' folder.
While debugging in Visual Studio this all works fine however when I publish and deploy the application to IIS I am getting the exception
Error saving file C:\windows\system32\config\systemprofile\Downloads(FILE NAME)
Could not find part of the path C:\windows\system32\config\systemprofile\Downloads(FILE NAME)
This is the current way I am getting the downloads folder:
FileInfo file = new FileInfo(Path.Combine(Environment.ExpandEnvironmentVariables(#"%USERPROFILE%\Downloads"), data.Filename + "." + data.FileType));
However I have also tried the solution that Hans Passant has answered to a similar question here. Both solutions worjk fine while debugging locally however as soon as I publish them, this one produces the exception:
Value cannot be null. Parameter name: path1
Which I presume is thrown at this point here when I try and save the file to the user's download folder.
using (var package = new ExcelPackage(file))
{
var workSheet = package.Workbook.Worksheets.Add("ExportSheet");
workSheet.Cells.LoadFromCollection(exports, true);
package.Save();
}
I don't really know how I would be able to reproduce these exceptions seeing as locally using Visual Studio it all works fine.
Has anyone else came across this issue while trying to download a file?
UPDATE: When the application is running on IIS, it seems to be using that as the user profile instead of the actually user, so when it tries to navigate to the Downloads folder, it cannot find it. How can I force it to use the user's profile?
LoadUserProfile is already set to True.
Web applications have no knowledge of the end-user's computer's filesystem!
So using Environment.GetFolderPath or Environment.ExpandEnvironmentVariables in server side code will only reveal the server-side user (i.e. the Windows Service Identity)'s profile directories which is completely separate and distinct from your web-application's actual browser-based users OS user profile.
As a simple thought-experiment: consider a user running a weird alien web-browser on an even more alien operating system (say, iBrowse for the Amiga!) - the concept of a Windows-shell "Downloads" directory just doesn't exist, and yet here they are, browsing your website. What do you expect your code would do in this situation?
To "download" a file to a user, your server-side web-application should serve the raw bytes of the generated file (e.g. using HttpResponse.TransmitFile) with the Content-Disposition: header to provide a hint to the user's browser that they should save the file rather than try to open it in the browser.

File.Exists() always returns false on IIS

The file path that I'm checking with File.Exists() resides on a mapped drive (Z:\hello.txt). The code runs fine in debug environment, however in IIS, it always returns false
var fullFileName = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["FileName"], fileName);
if (System.IO.File.Exists(fullFileName))
Why is this so, and how can I workaround this?
I have granted everyone full read/write permissions in that mapped drive
EDIT:
I tried deleting the file via \\192.168.1.12\Examples\Files\2.xml and I get the same result. It doesn't detect the file on IIS, but works fine on debug
I think your application do not has permission on "Z:"
Is "Z:" network disk?
I have had similar issues using network mapped drives, when running debug code application works perfectly and when running release version application cannot find the file.
If the files are stored on the same server as the application is deployed we found a solution by storing the local drive directory location of the mapped drive for example Z:\files\ could be E:\folder\folder1\
If the application is deployed on a separate server we found using the full network name works for example \\server1\folder\
I hope this proves helpful to you.
Your web application is running under a certain security context and you need to find out what context this is. If it's a normal user, open a command prompt as the user (using the runas tool), map the required drive using the command prompt (be sure to use the /persistent:yes flag)
Alternatively why can't you just use a UNC path (\\serverName\shareName) and avoid all this nonsense?
EDIT: 2013-05-27
To troubleshoot this, create a new application pool, based on whatever app pool you want. Then set the identity that this pool runs under as shown in the attached screenshot.
Make sure that this user has the correct privileges on the file share and then retest it
May be you should use Path.DirectorySeparatorChar

Upload files to a remote server

I need to upload files from my asp.net (C#) page residing in the web server to a remote server.
I managed to upload files to remote server from localhost using this code:
string serverPath = "\\\\xx.xxx.xx.xx\\Folder\\" + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(serverPath);
But after I published this code to my web server, it stopped working with the error "The network path was not found."
I have looked at a few solutions which suggest using UNC network share and implementing impersonation.
I couldn't figure out how to apply these solutions.
Can someone please give an example, or suggest a simpler solution.
Thanks!!
In FileUpload1.PostedFile.SaveAs(path), path is physical path of file, No Url. You must check:
is Physical folder Exsist?
is You have access to folder?
if answer of both question is true check this code:
string serverPath = #"\\xxx.xxx.xxx.xxx\Folder\";
if (!System.IO.Directory.Exists(serverPath))
System.IO.Directory.CreateDirectory(serverPath);
FileUpload1.PostedFile.SaveAs(serverPath + FileUpload1.FileName);
The account your application runs under must have write permissions to the folder you are trying to upload the file to: \\xx.xxx.xx.xx\Folder\. So you will have to configure the application pool in IIS to run under an account that will have sufficient permissions. Go to the application pool properties in the IIS management console where you will be able to specify an account to be used to run the application. By default it uses a built-in account which won't have any access to shared resources. Take a look at the following article which explains how to do so.
You need a virtual directory on your webserver to upload to. In code you'll have to use Server.Mappath("virtual path") function to get its server path and then save to it.

Access denied to path , when uploading image to folder in server

Am getting error when you are going to upload the file on specified folder in the server. Here I am going to upload P6100083.jpg in storeimg folder. When I am going to upload I am getting the following error:
Access to the path 'C:\inetpub\vhosts\bookmygroups.com\httpdocs\storeimg\P6100083.jpg' is denied.
Can anyone help me... How to use permisiion and were to use...
My code is while uploading image
if (FileUpload1.HasFile)
{
float fileSize = FileUpload1.PostedFile.ContentLength;
float floatConverttoKB = fileSize / 1024;
float floatConverttoMB = floatConverttoKB / 1024;
string DirName = "storeimg";
string savepath = Server.MapPath(DirName + "/");
DirectoryInfo dir = new DirectoryInfo(savepath);
// string savepath = "C:\\Documents and Settings\\ssis3\\My Documents\\Visual Studio 2005\\WebSites\\finalbookgroups\\" + DirName + "\\";
if (fileSize < 4194304)
{
string filename = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(filename).ToUpper();
if (extension.Equals(".jpg") || extension.Equals(".JPG") || extension.Equals(".JPEG") || extension.Equals(".GIF"))
{
savepath += filename;
FileUpload1.SaveAs(savepath);
}
}
}
Thanks in advance
I have no success making my upload or any write operation on filesystem work on IIS7.
Still getting the error: Access to the path is denied.
My AppPool is running under Network Service. I have granted all kinds of accounts Full Control (Network Service, Network, IIS_IUSR, Administrator, Users, Everyone), restarted the webservice several times, studied all IIS7 settings, googled for two hours and nothing works.
IIS7 and WS2008 s-u-c-k-s. Sorry for the term. Anybody can help?
I just wanted to add: I noticed that in the upload's destination folder's Properties there's this checkbox named "Read-only (Only applies to files in folder)" and it's checked. It cannot be unchecked, comes back checked after unchecking and clicking the OK button. Is that IIS7 guarding it?
Editing this message to add the SOLUTION: My admin has turned off the silly UAC "the security confirmation feature" on our server, restarted the machine and it works now. No "write" access rights for "Network Service" or any other IIS-used account was needed. When accessing the file system in a ASP.NET web application using the integrated authentication and having the impersonation set to true in its web.confing, the file system seems to be accessed by the authentified end-user's account, not by the Network Service account which the AppPool is running under. (Many people tell you to set Network Service permissions, but that is not true.) So you need to set the "write" permissions for your end-users (usually domain users: "DOMAIN\domain users") on your particular folder.
Oh yea, and the "Read-only (Only applies to files in folder)" checkbox mentioned above does not seem to have any effect. However Microsoft says "some programs might have problems writing to such folder and you should use command line statement "attrib -r -s" to get rid of the Read-Only attribute" -- but it won't work. It will stay there checked-grayed. But don't worry about that. Microsoft becomes more and more silly every day.
Indead, it's a server issue.
You need to verify if the user underlying your application pool has write access to the directory.
If you use IIS7, you have a new feature that helps you give custom write to this user and dun need to change the user.
Look at this link:
http://www.adopenstatic.com/cs/blogs/ken/archive/2008/01/29/15759.aspx
Hope this helps.
This is a server issue. Make sure you have the necessary rights to write files.
Btw, since you call ToUpper() on extension there's no reason to test for ".jpg".
If you are using Plesk Panel, go to file manager of Plesk Panel. List files and folders inside "httpdocs". Each file and folder has a lock icon at the very right. Click that of "storeimg" folder to change permissions. Click advenced button. Give full permission to these:
Plesk IIS WP User (IWPD_214(your_login_name))
Plesk IIS WP User (IWPD_214(your_login_name))
And click OK.
First you check the permission is enable or not if not then go to that folder which folder has to be use for containing files then right click on folder then there will be display folder properties then click on security there will be display multiple number of user which user have to be permit then click allow that all permission will be activated.
First, make sure your code runs fine locally (I assume that something you've already done).
Then deploy to your TEST or UAT environment. If you're having issue there, then this is a configuration issue. Make sure the service account under which your website's app pool is running has access to the folder.
Please make use of C# method Path.Combine() to build up your path and avoid issues with leading or trailing / and \.

Categories