Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access a file on the server in ASP.NET MVC

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.

like image 274
Jan Avatar asked Feb 26 '23 21:02

Jan


1 Answers

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
}
like image 127
Jess Avatar answered Mar 07 '23 22:03

Jess