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.
Related
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.
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.
I have a problem with starting the Excel Application under a particular user.
I try to schedule this script (C#) through an application X (not Windows Task Scheduler. And this application will always use a service account to run services on the server). If I run the C# script in command prompt under the same user, it runs. Under the application X, which uses the exact same user, to initiate the C# script, it fails to open the Excel application (not sufficient permission?).
This script calls:
app.Workbooks.Open(ExcelFileName,0,false,Type.missing....), yet it gives the following error:
Microsoft Excel cannot access the file "...". There are several possible reasons:
-The file name or path does not exist.
-The file is being used by another program.
-The workbook you are trying to save has the same name as a currently open workbook.
I tried all the methods that I found online to no avail.
Create directory “C:\Windows\SysWOW64\config\systemprofile\Desktop” (for 64 bit Windows) or “C:\Windows\System32\config\systemprofile\Desktop” (for 32 bit Windows). Then Set full control permissions on Desktop directory above (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user “IIS AppPool\DefaultAppPool”)
Changed the DCOM config for the Microsoft Excel application to include this user for Local/Remote Launch and Access
Enabled all macros in Excel and set the Trust Center.
Add the user to have full control on all folders that contain the Excel file.
Under DCOM config, Microsoft Excel Application, if I modify the Identity tab to check on "This User" and enter the username/password to let Excel always run under that user. Then the application runs perfectly. However, other users can't run the excel application on their own with the following error: "Cannot use object linking and embedding". If I check "Use the launching user", then Excel can't be launched. No errors in the logs or events anywhere to check.
Yet, still the same error. I think it's permission but I am not sure where and what to do for this to work.
Now, normally, when I run this excel report, I can double-click on the file and it'd automatically run, save the new parameters into the current file and generate a new excel file (with date attached to the file name). That means there is a change (save) to the original file.
I appreciate all your help!
I found the problem is the layer of security in the server!
Creating the Desktop folder inside the C:\Windows\System32\config\systemprofile and giving the service account permission to access the desktop folder is not enough.
I modified the C:\Windows\System32\config (or C:\windows\SysWOW64\config) folder to allow permission to the service account in security tab.
Then I also had to set up the same permission for the sub folder C:\Windows\System32\config\systemprofile (or C:\windows\SysWOW64\config\systemprofile) for the service account.
This works!
Microsoft Excel cannot access the file in Server 2012 Excel 2016.. checked various solutions online to create folder desktop in C:\Windows\SysWOW64\config\systemprofile\desktop.. didn't work for this but then i added a folder desktop in System32 and that definitely worked.
Since I have 64-bit Excel installed, the proper directory turned out to be the
c:\windows\system32\config\systemprofile\desktop
I ran across another way you can get this error: when you try to save a file with an "illegal" name, such as one with whacks (forward slashes) in it.
For that reason, it would seem reasonable that the err msg would give that as one possible explanation of the problem, but...no!
Specifically, I was trying to save a file named C:\RoboReporter\ABUELITOS\20160524_1327\ABUELITOS - Fill Rate - 4\1\61910B10
The whacks (shown as backwhacks in the copied exception text, but seen as forwardwhacks when hovering over the value when debugging) were the cause of the discombobulation. Once I fixed that by replacing whacks with underscores:
filename = String.Format("{0}\\{1} - Fill Rate - {2}.xlsx", uniqueFolder, _unit, _begDate.ToShortDateString());
filename = filename.Replace("/", "_");
...all went swimmingly.
I have the code to save a file in a folder in directory
string timestamp = DateTime.Now.ToString("MM-dd-yyyy.HH-mm-ss");
var file = File.Create("Owe-Data.txt" + timestamp);
var com = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase + timestamp + #"\Data" + file;
MessageBox.Show(com);
if (!Directory.Exists(com))
{
Directory.CreateDirectory(com);
}
using (var sw = new StreamWriter(com))
{
sw.WriteLine(InputData);
}
}
i Displayed COM it gives path bt i cant see the Data folder or Owe-Data file at that path
Anybody can tell why this happening, or should i save the Data folder in current directory where this prgram running? bt i dnt know how to reach that path. Any solutions ??
Working on windows phone 5, visual studio 2008 .NET framwork 2.0
As per the Exceptions section of documentation,the above exception is thrown when
ArgumentException ------- folder is not a member of System.Environment.SpecialFolder.
It means the OS where you are running this command does not have Environment.SpecialFolder.CommonApplicationData as one of the special folder.
For knowledge,
Environment.SpecialFolder.ApplicationData is the most common one. This folder holds per-user, non-temporary application-specific data, other than user documents. A common example would be a settings or configuration file.
Environment.SpecialFolder.CommonApplicationData is similar, but shared across users. You could use this to store document templates, for instance.
Environment.SpecialFolder.LocalApplicationData is a non-roaming alternative for ApplicationData. As such, you'd never store important data there. However, because it's non-roaming it is a good location for temporary files, caches, etcetera. It's typically on a local disk.
I think the problem may be that Environment.SpecialFolder.CommonApplicationData is common and shared between different users and the user with which you have logged in is not having rights to access the folder or the Visual Studio has not been started in Admin mode.
EDIT Look at link and try to add a manual registry Common AppData defined in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\
Given you are asking about a .NET Windows Phone application as per the tags
I think your problem is that a .NET Windows Phone application does not have direct access to the file system; it can only access IsolatedStorage this is by design.
I would quote a Microsoft source for this but I can't seem to find one!
EDIT
See this article from MSDN
I am using ItextSharp and I am getting a new font for it by doing this
string fontPath = Path.GetFullPath("C:\\BMSApplicationFiles\\Fonts\\FREE3OF9.TTF");
BaseFont barCodeBase = BaseFont.CreateFont(fontPath, BaseFont.CP1252, BaseFont.EMBEDDED);
That file is in that directory on both my dev machine and the server.
When i run this on my dev machine it works fine, when published to my server I get an error saying FREE3OF9.TTF is not found as a file or a resource.
I have double and triple checked that the file is in fact there on my server. My application has full trust on IIS.
and IIS user has full access to this folder. And still I get this error. Very frustrating.
Any ideas??
This code is Not inside the Web Application but inside a DLL class library that the web application is referencing. Do I need to add any more special permissions or something?
Your next step should be to confirm that what you think is happening is happening. If you are allowed to, download and install Process Monitor which will allow you to log activity including which files are being attempted to be accessed and by which user account. Apply filters when monitoring of course, or else you'll end up seeing all the activity on the server...
If that only confirms that the correct file is being attempted to be read by expected user then maybe there's something up with the font. Try replacing the font file temporarily with another standard one (e.g. arial or something) and see what happens. (this is unlikely to help as it works on your dev machine, but might be worth a go)
Most probably you have a security issue.
If you run IIS7 then check that IIS_IUSRS group has an access to the file (open file properties in explorer select Security tab etc).
If you run IIS6 then check that IUSR_MachineName account has an access to the file.
I had a similar error when I tried to get it working with IIS. Within IIS, I had to add he file directory as a virtual drive. That worked for me when I had a similar situation set up. Hopefully it works for you, best of luck