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 = @"~\Tem开发者_JAVA百科plates\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.
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
}
You need to use Server.MapPath(path)
string templatePath = Server.MapPath("~/Templates/report.xlsx"); //Note the forward slashes instead of backslashes.
using (var template = File.OpenRead(templatePath)) {
// Copy template and process content
}
This will map the virtual directory path to the full path on the server.
精彩评论