Home > front end >  Get file path to image on Azure Asp.Net core server (in controller)
Get file path to image on Azure Asp.Net core server (in controller)

Time:04-09

I know this is probably an easy task, but I have been now trying several approaches without success. I have controller named AuthorizeController.cs. Inside this controller I would like to specify default avatar image for registered users.

I do this way in constructor:

  private IWebHostEnvironment WebHostEnvironment { get; }
  private byte[] ProfilePicture { get; set; }

  this.ProfilePicture = System.IO.File.ReadAllBytes(
    string.Concat(this.WebHostEnvironment.WebRootPath, @"\Resources\avatar.png"));

My image is located inside the same project:

MrDashWeb.Server
 - Resources
    - avatar.png 

On my local machine, when I run it in localhost, everything works fine. However after uploading this into Azure, I am getting an errors in Log Stream:

If the exception handler is expected to return 404 status responses then set AllowStatusCode404Response to true.---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Resources\avatar.png'.at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)

What I am doing wrong and how to fix it?

CodePudding user response:

Please create below interface to get the WebRootPath. The value of WebRootPath should be D:\home\site\wwwroot\wwwroot

CheckPath():

public string CheckWebRootPath()
{
    string wwwPath = _webHostEnvironment.WebRootPath;
    return wwwPath;  
}

Test Result:

enter image description here

I also test your code like below, and I think your code is correct.

public string CheckFile()
{
   string wwwPath = _webHostEnvironment.WebRootPath;
   var ProfilePicture= System.IO.File.ReadAllBytes(
          string.Concat(wwwPath, @"\Resources\avatar.png"));
   return ProfilePicture.Length.ToString();
}

Suggestion

  1. Check the value of WebRootPath, if the value is C:/, please recreate a new webapp in azure portal.

  2. If your webapp name is testapp, then the webapp url should be

    https://testapp.azurewebsites.net
    

    Then you can check your file via below url

    https://testapp.scm.azurewebsites.net
    

    enter image description here

  • Related