LoginSignup
1
0

More than 1 year has passed since last update.

Azure functionsでプロジェクト内のファイルを読み込む

Posted at

AzureFunctionsでファイル(テキスト)とか読み込んで使いたい時

もちろんsettings.jsonに環境変数とか入れられるんだが、JSONとかわりと内容が多いときに困る。
そういうときのTips

MacとWindowsではパスの表現が違います。

まずここ注意、最近VSとかもMacで使えるようになって便利なんだけど、ここは相変わらず同じにはできない(当たり前)
Mac(Linux)とWindowsで書き方変えるのもいただけない、そんなときの表記はこちら。
System.IO.Path.Combine(context.FunctionDirectory, "..", "hoge", "foo.json")
これでパスセパレータとかよしなにやってくれます。

たぶん相対パスでも辿れるはずだが…

念の為、このように変更しましょう。

func.cs
namespace Api
{
    public static class BAWColumnName
    {
        [FunctionName("hoge")]
        public static async Task<IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
            HttpRequest req, ILogger log, ExecutionContext context)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string text = System.IO.File.ReadAllTextAsync(System.IO.Path.Combine(context.FunctionDirectory, "..", "static_json", "some.json")).Result;

            return new ContentResult(){Content = text, ContentType = "application/json"};
        }
    }
}

ExecutionContext contextをRunAsyncの引数に追加してます。

忘れずに

読み込むべきファイルはプロジェクト設定で、かならず出力フォルダに含めるようにしましょう。
これを結構忘れていつまでも上手く行かないときがある…

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0