Accessing a file on a server in ASP.NET MVC

In my ASP.NET MVC application, I create excel reports, I have a template file that I copy and modify. This template file is placed 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 throws an exception

 Couldnot find a part of the path 'C:\Templates\report.xlsx'.

How do I access this file?

I also tried using

string templatePath = @"~\Templates\report.xlsx";

But this leads to

Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Templates\report.xlsx'.

However, it works when I use the absolute path, but it does not make sense for my production server.

+3
source share
2 answers

I believe that you will do this in the usual 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
}
+8

Server.MapPath()

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
}

.

0

Source: https://habr.com/ru/post/1773262/


All Articles