Reputation: 1181
I have a functionality in my web application that let the users download some help documents by clicking on the document name. Recently I made a change in my project, I kept all the pdf files in my wwwroot folder instead of keeping them on some directory on the server. I kept them in the following hierarchy wwwroot > Assets > ConnectHelpDocuments. Now after deploying the application for some reason when I click on the file It says "Access to the path 'C:\Webs\Engage\API\wwwroot\Assets\ConnectHelpDocuments\xxxxx.pdf' is denied". It works fine on my localhost. Here's the code snippet that tries to read from the wwwroot and then send that as a file.
private const string ResourceDocument = @".\wwwroot\Assets\ConnectHelpDocuments\";
[HttpGet("DownloadDocument/{fileName}")]
[TypeFilter(typeof(AsyncUserActionFilter))]
[System.Web.Mvc.ValidateInput(true)]
public async Task<IActionResult> DownloadDocument(string fileName)
{
try
{
string filePath = Path.Combine(ResourceDocument, fileName);
if (!System.IO.File.Exists(filePath))
return NotFound();
var memory = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(filePath), fileName);
}
catch (Exception ex)
{
this.logger.LogError(ex.Message);
return BadRequest(ex.Message);
}
}
I am also attaching the screenshot of the project folder structure which shows the folders
Can anyone help me identify the reason? Is there any settings on the IIS that I need to tweak ? I don't have much access here otherwise I would have pasted the IIS settings as well.
Upvotes: 0
Views: 3105
Reputation: 406
Did you find a solution yet?
IWebHostEnvironment
WebRootPath
You can find the path of your file using the WebRootPath of IWebHostEnvironment. You will need to include this in your program/startup file. For example:
private readonly IWebHostEnvironment _environment;
public Startup
(
IWebHostEnvironment environment
)
{
_environment = environment;
}
And:
public class TestService : ITestService
{
public static IWebHostEnvironment _environment;
public TestService
(
IWebHostEnvironment environment
)
{
_environment = environment;
}
private MemoryStream Attachment()
{
MemoryStream stream = new();
try
{
string path = _environment.WebRootPath;
path += "/Assets/ConnectHelpDocuments/Testfile.pdf";
byte[] testByte = File.ReadAllBytes(path);
stream = new(testByte, false);
}
catch (Exception exceptionTest)
{
Error_General(exceptionTest);
}
return stream;
}
}
Also: please check whether your file properties is set to content. Otherwise it's not included in the publish.
Hope this helps.
Kind regards.
Upvotes: 1