.Net 6 IWebHostENvironment returns local path that exists on server

Abdelrahman Tarek 21 Reputation points
2022-11-20T19:58:23.887+00:00

I have a .net core web api deployed on smarter ASP.net services, in my web api I save images and files by adding them to a predefined folder in wwwroot file that exists in the presistance project, and then i save the url in SQL database. This is my code to save the file and get the url using IWebHostEnvironment, after sending the request the saved url is like this "h:\root\home\siteurl\OriginalForms\MySavedFile", This is the path for the file on the server itself, i want to save the url itself like "http://MyDomain//Folder//File" not the local one on the server.

MyCode : var path = Path.Combine(_webHostEnvironment.WebRootPath "OriginalForms",request.FormName); using (FileStream stream = new FileStream(path, FileMode.Create)) { await request.Form.CopyToAsync(stream,cancellationToken); } OriginalForm.Url = path

Developer technologies | ASP.NET | ASP.NET Core
SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-11-21T06:27:49.477+00:00

    Hi @Abdelrahman Tarek ,

    You should build the file path by yourself. Refer to the following sample:

            var foldername = "images";  
            var filename = "Image1.png";  
            var path1 = Path.Combine(_environment.WebRootPath, foldername, filename);  
            var path2 = Path.Combine("\\", foldername, filename);   
            var location = new Uri($"{Request.Scheme}://{Request.Host}/{foldername}/{filename}");   
            var url = location.AbsoluteUri;   
    

    If you want to upload/download file from the wwwroot folder, you can get the file path via the IWebHostENvironment.

    If you want to display the image using image control, you can use the relative paths, such as path2 in the above sample.

    If you want to store the file path using the request host, directly build the request url, like the path3:

    The result as below:

    262369-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.