How to include resource files in vscode azure functions?

Viewed 122

I have vscode linked with my azure account via the integrated azure functions extension, functions are in C#. Functions work as expected both locally and on the cloud via the "deploy to function app..." button. My question is, how can I have some files included with the deployment to be used as resources (such as text files) when some of the functions run? I can see how this could be done with visual studio, but I have not figured out how it is done with visual studio code and the azure functions extension.

1 Answers

Probably better ways to do it but if you've been using plugins like nuget package manager in vscode, you can just add a CopyToOutputDirectoty element into the xxxxx.csproj file it will create (It uses the same approach as you would in visual studio)

eg I added the last entry in the file manually

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
    <PackageReference Include="DocumentFormat.OpenXml" Version="2.17.1" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
    <None Update="data/sample.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

Then use something like this to read the file in C#

string responseMessage = File.ReadAllText(Path.GetFullPath(Path.Combine(context.FunctionDirectory, "..\\data\\sample.json")));
Related