.NET FileNotFoundException on correct path?

Viewed 43

I'm trying to serve a PDF in my application like this

    string[] paths = {Environment.CurrentDirectory, "Content", "HelpDoc.pdf"};
    string filePath = Path.Combine(paths);
    try
    {
        return File(filePath, "application/pdf");
    }
    catch (FileNotFoundException e)
    {...}

However, when hitting this in the browser, I get a "FileNotFoundException: Could not find file: C:\Users...".

  • If I copy the path from the exception message into my File Explorer, it pulls up the correct file with no issue
  • In my project, I've ensured the PDF's property "CopyToOutputDirectory" is "Copy always"
  • I've verified several times over that the path matches the location in both my File Explorer and Rider's copy path option

I feel like I'm losing my mind over this, does anyone have any suggestions?

1 Answers

For others having the same issue, I moved my pdf to a new directory called "pdf" inside the wwwroot directory. I then was able to access it like this:

string[] paths = {"wwwroot", "pdf", "HelpDoc.pdf"};
string filePath = Path.Combine(paths);
byte[] pdfBytes = System.IO.File.ReadAllBytes(filePath);
MemoryStream memoryStream = new MemoryStream(pdfBytes);
return new FileStreamResult(memoryStream, "application/pdf");
Related