How to use Server.MapPath in core

Server.MapPath is not available in core. Instead, you can use IWebHostEnvironment interface to access any physical contents kept in the specified path.

Below is the Controller code using the IWebHostEnvironment ContentRootPath property which gets the absolute path to the directory that contains the Application content files:

public class DocumentController : ControllerBase
	private IDocumentService offService = null;
	private readonly IWebHostEnvironment _host;

	public DocumentController(IDocumentService offService, IWebHostEnvironment host)
		this.offService = offService;
		this._host = host;
	public IActionResult ExportToFile([FromQuery] int UserId)
		var username = HttpContext.User.Identity.Name.Split('\\')[1].ToString();
		//get the memoryStream by passing the absolute path:
		MemoryStream memoryStream = offService.GetWordStream(_host.ContentRootPath);
		memoryStream.Position = 0;
		return File(memoryStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "File.docx"); // returns a FileStreamResult

Use the path in the File IO methods, example below:

File.Copy(path + "\\DocPath\\File.docm", strFileName);

In the debug mode, this path is the WebAPI Project absolute path to the directory. During runtime, this path is the absolute path where the files are hosted on the Server.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.