How To Access Azure Functions wwwroot Folder

How To Access Azure Functions wwwroot Folder

In this Azure tutorial, we will discuss How To Access Azure Functions wwwroot Folder. Along with this, we will also discuss a few other topics like Azure Function Get Current Directory, How To Refer A File In Azure Function, Azure Function Write To Blob, Azure Function File System, Azure Function Get Base URL and we also discussed Azure Function Access To The Path Is Denied and Azure Function save the file locally.

How To Access Azure Functions wwwroot Folder? There are some ways to access Azure functions wwwroot folder. The best and easy way is

  • Using the Advanced Tool (Kudu)

Below, we will discuss in detail on the steps to access the wwwroot folder.

How To Access Azure Functions wwwroot Folder

Advanced Tool (Kudu) is an excellent tool that helps us to access the wwwroot directory using the Azure Portal. Follow the below steps to know How To Access Azure Functions wwwroot Folder.

Log in to the Azure Portal (https://portal.azure.com/).

The next step is, Go to your Azure Function app that you have created in the Azure Portal. Under the Development Tools section, click on the Advanced Tools link.

Import PowerShell Module or Package into your Azure Function App

Click on the Go button on the Advanced Tools window as shown below.

How To Add Custom Modules In The Azure Functions App

You can able to see Debug console DropDown on the top of the page, select the CMD option from that dropdown.

Add Custom Modules In The Azure Functions App

Click on the Site folder from the below window as highlighted.

How To Access Azure Functions wwwroot Folder using Kudu

Here is the wwwroot folder that you want to access using the Kudu advanced tool.

Access Azure Functions wwwroot Folder using Kudu

If you will click on the wwwroot folder, you can able to see your function as highlighted below. Click on your Function name to see your available files and folders.

How to Access Azure Functions wwwroot Folder using Kudu tool

You can able to see the files and folders for my Azure Function as shown below. You can click on the download button as highlighted to download any of the files as shown below.

How to Access Azure Functions wwwroot Folder using Kudu tool in Azure Portal

In the Kudu Remote Execution Console, you can able to see the complete path to your Azure function.

D:\home\site\wwwroot\MyHttpPowerShellFunction> 

How to view Azure Function files deployed

Azure Function Get Current Directory

Above we discussed How To Access Azure Functions wwwroot Folder. Now let’s discussed How to get the Current Directory Azure Function in Visual Studio 2019. You can do the following changes in your Azure function to Get the current Directory

The first thing is

  • The first thing is the ‘ExecutionContext context’ we need to use in our Azure function signature as a parameter.
  • The next thing is we will use the ExecutionContext.FunctionAppDirectory inside our Azure Function code to get the Current Directory.

How To Refer A File In Azure Function?

Now let’s see an example. Below is my Azure Function to just to show How to access the Azure Function Code in Visual Studio 2019. You can add the return statement based on your business needs.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace MyNewHTTPAzureFunction
{
    public static class MyNewHTTPAzureFunction
    {
        [FunctionName("MyNewHTTPAzureFunction")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");




            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;



            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            //This is how you can access the curent Directory with the help of context.FunctionAppDirectory

            string localFile = Path.Combine(context.FunctionAppDirectory, "Data", "FunctionFile.txt");
            string readLocalFile = File.ReadAllText(localFile);

            // Write the return code based on your Business needs
            //
            //

            return new OkObjectResult(responseMessage);
            
        }
    }
}

You can check out the below high lighted lines of code for the implementation to access the Azure Function Current Directory. Function logic you can add based on your business needs.

Azure Function Get Current Directory

No Access To ExecutionContext

There might be one more case i.e if in case you don’t have access to the ExecutionContext. In that case, you might be thinking about how to access the current directory of the Azure Function because the above-mentioned approach will not work out in this case.

So here is another way to access the current directory of the Azure function if you don’t have access to the ExecutionContext.

You can read the local file in your Startup class like below.

var binpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var rootpath = Path.GetFullPath(Path.Combine(binpath, ".."));

///Read the file
File.ReadAllText(rootpath + "/path/to/Mynewfile.txt");

Azure Function Write To Blob

Well, here we will discuss how to write the file or data to the Blob from the Azure function. We need to do the following changes for the Azure Function Write To Blob functionality.

The first thing is we need to do some configuration changes to the local.settings.json file. One important point to note down here is we need to mention the “direction” value as “inout” for the write or read operation for Blob.

Now Your local.settings.json file should look like below. Of course, you need to change the values based on your filename or container name, etc.

{
  "type": "blob",
  "name": "NewBlob",
  "path": "Democontainer/newblob.txt",
  "connection": "The name of your Azure Storage connection",
  "direction": "inout"
}

Now on the class file where you have written your Azure Function

You need to add the below name space for the CloudBlockBlob

using Microsoft.WindowsAzure.Storage.Blob;

Then we need to pass the parameter CloudBlockBlob NewBlob as mentioned below.

public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous,"post", Route = null)] HttpRequest req,
            ILogger log, CloudBlockBlob NewBlob)

Then you can add the below code in your Azure function to write to the Blob storage.

byte[] file = System.Text.Encoding.UTF8.GetBytes("Add this");
NewBlob.UploadFromByteArray(file, 0, file.Length);

Azure Function File System

Azure function app has different file system storage locations. Well, let’s discuss on those.

D:\local

This is local temporary storage and you cannot share any file from this storage. Temporary storage meaning, this storage goes away as soon as you delete your Azure function from the Virtual Machine. You can store up to 500MB data here.

If your Azure function has to say 3 instances, each one of these instances will actually run on its own virtual machine, and ultimately, each instance will have its own D:\local storage up to 500MB.

D:\Home

This storage is shared storage. There are no restrictions, All your Azure Function app instances will have access to this storage. In this storage case, If you will delete your Azure function app or moved it to somewhere else then the storage will not go away like in the case of D:\local. The storage will remain as it is.

So these are all about the Azure Function app multiple file-system storage locations.

Azure Function Get Base URL

You can get the Azure Function Base URL using the req.originalUrl. So if you are creating an Azure function app using the Node.Js and using the language as javascript while creating an Azure Function, then, in that case, you can use the req.originalUrl; to get the Base URL of your Azure function or to test this scenario, You can follow the below steps.

Basically you need to create an Azure HTTP trigger function using JavaScript as a programming language.

Once you have created your HTTP triggered function, if you will navigate to that function, you will see a file called index.js where your Azure Function actually exists. So in that function code, you can add the below line of code to get the function base URL.

No navigate to your Azure Javascript HTTP triggered function and click on the Code + Test link from the left navigation and then add the below line of code to your Azure function code.

context.log(req.originalUrl);

Now below is my Azure Function complete code.

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    context.log(req.originalUrl);

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

Now after the code change, you can click on the Test/Run button from the top navigation and then provide the a value for the name parameter and then finally, click on the Run button to run the function. You can refer to the below screenshot.

Now if you can see the logs as highlighted below, we got the Base URL for our Azure Function.

Azure Function Get Base URL

This is how we can able to access the Azure Function Base URL.

Azure Function Access To The Path Is Denied

Many times, some of us use to get this error while doing any operations with different local files in case of Azure Function, we use to get the error Azure Function Access To The Path Is Denied.

To avoid this type of error in case of Azure functions, remember one important thing here, Always try to keep your files in the D:\home\site\wwwroot directory that is exactly where exactly the Azure Function resides. This is what the suggested approach.

Azure Function save file locally

Consider a scenario, where you have a local file and you want to refer it in the Azure Function. So you need to do the following stuff for that

  • First, copy the local file and keep it in the Azure Function root directory.
  • Then we need to set the property of that file i.e CopyToOutputDirectory to PreserveNewest.
  • Now use the ExecutionContext context as the Azure function parameter so that you can get access to the context.
  • Now you can use the context.FunctionAppDirectory appending the file name to access the file inside your Azure function.
ExecutionContext context

Now if you will implement the above changes, then your Azure function should look like below

  [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            log.LogInformation("hello log");

            var data = File.ReadAllText(context.FunctionAppDirectory + "/TestFile.txt");

            string name = req.Query["name"];

You can see the changes here as below

Azure Function save file locally

And the same file, in case if you want refer it from any path locally then you can do the below changes, But this is not a suggested approach

You can do the below changes in your AzureFunctionProject.csproj file.

Right click on your Azure Function Project and then select Edit Project File option.

azure function read local file

Now you need to add the below line of code as it is

<ItemGroup>
    <None Include="E:\\ProjectDoc\\Result.txt">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

It should look like below

how to store file in azure function

This is how you can read from file azure function locally.

You may also like following the below articles

Wrapping Up

Well, in this article, we discussed How To Access Azure Functions wwwroot Folder, Azure Function Get Current Directory, How To Refer A File In Azure Function, Azure Function Write To Blob and we also discussed Azure Function File System, Azure Function Get Base URL and finally, we discussed Azure Function Access To The Path Is Denied and Azure Function save the file locally.