access a file on the server in ASP.NET MVC
11,220
I believe you would do it the normal ASP.NET way, assuming Templates is a directory in your web application.
string templatePath = @"~\Templates\report.xlsx";
using (var template = File.OpenRead(Server.MapPath(templatePath))) {
// Copy template and process content
}
Related videos on Youtube
Comments
-
Jan almost 2 years
In my ASP.NET MVC application I am generating excel reports, I have a template file that I copy and alter. This template file is put in a folder in my solution. I want to use it as follows:
string templatePath = @"\Templates\report.xlsx"; using (var template = File.OpenRead(templatePath)) { // Copy template and process content }
But This code generates an exception
Couldnot find a part of the path 'C:\Templates\report.xlsx'.
How should I reference this file?
I also tried using
string templatePath = @"~\Templates\report.xlsx";
But that results in
Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Templates\report.xlsx'.
It does work however when I use the absolute path but that is meaningless to my production server.
-
Janvi Patel over 13 yearsIf you use the tilde in the path it is important you call
Server.MapPath
on the string to resolve it.
-
-
Charlino over 13 yearsWhat about trying it this way
Server.MapPath("/Templates/report.xlsx")
... ? Hang on... you just deleted your comment saying it didn't work. Did it? -
Jan over 13 yearsI didn't read his answer very well at first. He has put it inside of the
File.OpenRead()
. Putting that statement on the assignment is cleaner code in my opinion but that's personal flavor. -
Jan over 13 yearsbackslashes work for me, can you explain why forward slashes are better?
-
Chev over 13 yearsGuess I've never tried it with back slashes. Back slashes usually represent an actual physical path while forward slashes represent the virtual directory that houses your application. Server.MapPath() takes a virtual directory on the same server and maps it to it's fully qualified physical path. Maybe it's smart enough to know what you are intending to do and that's why backslashes work. I'm not entirely sure.
-
Chev over 13 yearsI bet I know why it works. Templates\report.xlsx is a physical subdirectory of your root virtual directory so it's working. However, I bet if the Templates directory was only a virtual subdirectory of your root virtual directory and that the physical directory was somewhere else then backslashes would not work. I should test this out sometime. If that's the case then I would still recommend forward slashes just in case you ever need to move your directory structure around while leaving your virtual directories the same..