I don't want to raise this as an issue / bug on the git page as I imagine I am simply using the package wrong.
I have an ASP MVC site running on IIS10. Actual folder structure is:
x:/
library/ <-- Physical
Web Sites/
Site A/
Files/ <-- Virtual
Site B/
Site C/
And using IIS10, I've made a virtual folder called Files under Site A, of which the physical path is X:/library/ (the reason for this is to share resources between sites and to take the content outside of the web-site path).
Users are able to upload / download files to / from the virtual directory fine. I can load images from there without issue also.
However, I cannot seem to get Rotativa to write to the virtual directory from within my application. Obviously command line does not see the virtual directory anyway, but creating a file from cmd to the physical directory works fine.
From within the app though:
X:/Web Sites/Files/Test.pdf results in Unable to write to destination
X:/library/Test.pdf results in Access to the path is denied (despite already giving NETWORK SERVICE full control of the library folder and sub-folders)
The code I am using is:
var pdf_output= new ActionAsPdf("Summary", new { id = id }) {
FileName = String.Format("Summary_{0}.pdf",id.ToString()),
CustomSwitches = "--print-media-type"
};
byte[] pdf_data= pdf_output.BuildPdf(ControllerContext);
System.IO.File.WriteAllBytes(String.Format("xxx",id.ToString()), pdf_data);
with a variety of directory path combinations in place of "xxx".
Has anyone had any experience with this before that might show me where I am going wrong? Any help would be greatly appreciated.
Never mind, solved it. I needed to grant the respective Application Pool permission to the physical library directory by adding the user IIS AppPool\Site A.
Related
I am currently trying to create a web service application using Visual Studio 2022 ASP.NET Webforms application with a service reference. The goal is to take in information and store it as a text file on the local machine within the project folder so it is accessible by the web service on my local server.
I have successfully created the text files and can access them on my local machine, but when I navigate to the text file on my local server tree I get an HTTP Error 404.0 which is shown below. I need any user who accesses my server to be able to access the saved text files. I have tried to change security privileges on the folder and in my web.config file, but have not had any luck. I would appreciate any suggestions someone may have.
Here is my code for where I save the information as a text file.
// Randomly generate string for text file name
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var textFile = new char[4];
var random = new Random();
for (int i = 0; i < textFile.Length; i++)
{
textFile[i] = chars[random.Next(chars.Length)];
}
eventFile = "\\";
eventFile += new String(textFile);
eventFile += ".txt";
folderPath = Server.MapPath("~/Events");
File.WriteAllText(folderPath + eventFile, fullEventDetails);
Both my URL and local file path are the following:
URL https://localhost:44399/sx1l.txt
Path Name \\Mac\Home\Desktop\Homework3\Homework3\sx1l.txt
Ok, so you have to keep in mind how file mapping works with IIS.
Your code behind:
that is plane jane .net code. For the most part, any code, any file operations using full qualified windows path names. It like writing desktop software. For the most part, that means code behind can grab/use/look at any file on your computer.
However, in practice when you use a full blown web server running ISS (which you not really doing during development with VS and IIS express)? Often, for reasons of security, then ONLY files in the wwwroot folder is given permissions to the web server.
However, you working on your development computer - you are in a effect a super user, and you (and more important) your code thus as a result can read/write and grab and use ANY file on your computer.
So, keep above VERY clear in your mind:
Code behind = plane jane windows file operations.
Then we have requests from the web side of things (from a web page, or a URL you type into the web browser.
In that case, files are ONLY EVER mapped to the root of your project, and then sub folders.
So, you could up-load a file, and then with code behind save the file to ANY location on your computer.
However, web based file (urls) are ONLY ever mapped though the web site.
So, in effect, you have to consider your VS web project the root folder. And if you published to a real web server, that would be the case.
So, if you have the project folder, you can add a sub folder to that project.
Say, we add a folder called UpLoadFiles. (and make sure you use VS to add that folder). So we right click on the project and choose add->
So, you right click on the base project and add, like this:
So, that will simple create a sub folder in your project, you see it like this:
So, the folder MUST be in the root, or at the very least start in the root or base folder your project is.
So, for above, then with UpLoadFiles, then any WEB based path name (url) will be this:
https://localhost:44399/UpLoadFiles/sx1l.txt
(assuming we put the file in folder UpLoadFiles).
But, if you want to write code to touch/use/read/save and work with that file?
You need to translate the above url into that plane jane windows path name. (for ANY code behind).
So, if I want to in code read that file name?
Then I would use Server.MapPath() to translate this url.
say somthing like this:
string strFileName = "sx1l.txt";
string strFolderName = "UpLoadFiles"
string strInternaleFileName = server.MapPath(#"~/" + strFolderNme + #"/" + sx1l.txt";
// ok, so now we have the plane jane windows file name. It will resolve to something like say this:
C:\Users\AlbertKallal\source\repos\MyCalendar\UpLoadFiles\sx1l.txt
I mean I don't really care, but that web server code could be running on some server and that path name could be even more ugly then above - but me the developer don't care.
but, from a web browser and web server point of view (URL), then above would look like this:
https://localhost:44392/UpLoadFiles/sx1l.txt
And in markup, I could drop in say a hyper link such as:
UpLoadFiles/sx1l.txt
So, keep CRYSTAL clear in your mind with working with path names.
Web based URL, or markup = relative path name, ONLY root or sub folders allowed
code behind: ALWAYS will use a plane jane full windows standard file and path.
But, what about the case where you have big huge network attached storage computer - say will a boatload of PDF safety documents, or a catalog of part pictures?
Well, then you can adopt and use what we call a "virtual" folder. They are pain to setup in IIS express, but REALLY easy to setup if you using IIS to setup and run the final server where you going to publish the site to.
Suffice to say, a virtual folder allows you to map a EXTERNAL folder into the root path name of your side.
So, you might have say a big server with a large number of PDF docuemnts,
say on
\\corporate-server1\PDF\Documents
so, in IIS, you can add the above path name, say as a folder called PDF.
Say like this:
So, WHEN you do the above, then the folder will appear like any plane jane folder in the root of the project, but the file paths can and will be on a complete different location OUTSIDE of the wwwroot folder for the web site.
So, now that we have the above all clear?
\\Mac\Home\Desktop\Homework3\Homework3\sx1l.txt
But, your code has this:
folderPath = Server.MapPath("~/Events");
File.WriteAllText(folderPath + eventFile, fullEventDetails);
(you missing the trailing "/" in above, you need this:
File.WriteAllText(folderPath + #"/" + eventFile, fullEventDetails);
So, that means the url for the text file will then be:
https://localhost:44399/Events/sx1l.txt
And if you using Visual Studio to add files to that folder (add->existing items), then MAKE SURE you Build->rebuild all (else the file will not be included in the debug run + launching of IIS express.
So, given that you saving into a folder called Events (as sub folder of wwwroot, or your base folder for hte web site, then the above is the url you should use, but your code always was missing that "/" between folder and file name.
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.
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 written a server in C# for a JS client.
The Solution consists restApi BL and DAL.
The BL creates links for images stored on a virtual directory, on the server.
The JS and the server code, are stored in the same directory.
When I build the string of the link I use this line of code:
string keyImageName = Settings.Default.ServerUrl +
Settings.Default.KeyImagesFolder + relatedFinding.KeyImagePath;`
where KeyImageFolder is a virtual directory.
It works fine, but my problem is that the website has multiple Amazon instances, one for each geographical zone , so every time I deploy, I need to change the ip in the settings.it's annoying.
Is there a way to get the virtual directory's url, specifically for each machine?
if the JS is installed on the same machine as the server, does it really need a full path?
Many thanks
First, you'll need to get the physical path for the file or directory that you want to generate a url for. This can be done within a Page object using Request.ApplicationPath.
Next, this path can be converted to a url path using the Server.MapPath function. This will take into account if there are more than one websites tied to the same path in IIS.
var physicalPath = Path.Combine(Request.ApplicationPath, Settings.Default.KeyImagesFolder, relatedFinding.KeyImagePath);
var resourceUrl = Server.MapPath(physicalPath);
I need to create a folder to use for storing files within it, in a .Net MVC3 application, but I think the problem is common to all ASP.Net platform.
Problem is I can create the folder, but cannot write the files, because System.UnauthorizedAccessException occurred.
I also tryed givin extra permission to the user currently running the web app, but nothing changes.
This is my code so far:
if (!System.IO.Directory.Exists(fullPath))
{
System.IO.Directory.CreateDirectory(fullPath);
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
var dirInfo = new System.IO.DirectoryInfo(fullPath);
var sec = dirInfo.GetAccessControl();
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
System.Security.AccessControl.FileSystemRights.Modify,
System.Security.AccessControl.AccessControlType.Allow)
);
dirInfo.SetAccessControl(sec);
System.IO.Directory.CreateDirectory(fullPath);
}
string fullPathFileName = System.IO.Path.Combine(fullPath, fileName);
System.IO.File.WriteAllBytes(fullPath, viaggio.Depliant.RawFile);
Too bad, last line of code always throw System.UnauthorizedAccessException.
I'm not impersonating user in my app, everything run under a predefined user.
What should I do to create a folder and assure that the application can also create files within it?
Edited:
I also tryed to save the files in the App_Data special folder, but I still got the System.UnauthorizedAccessException error. Somebody can tell me why is that happening?
I hate to answer my own question when the problem is that stupid...
I'm just trying to save a file without a proper filename: you can see I'm using the fullPath variable both for creating the folder and for saving the file, instead of using the correctly created fullPathFileName.
Blame on me!
Use App_Data folder, quote from http://msdn.microsoft.com/en-us/library/06t2w7da%28v=vs.80%29.aspx :
To improve the security of the data used by your ASP.NET application, a new subfolder named App_Data has been added for ASP.NET applications. Files stored in the App_Data folder are not returned in response to direct HTTP requests, which makes the App_Data folder the recommended location for data stored with your application, including .mdf (SQL Server Express Edition), .mdb (Microsoft Access), or XML files. Note that when using the App_Data folder to store your application data, the identity of your application has read and write permissions to the App_Data folder.