webjob 在本地和生产环境中读取文件

webjob read file locally and in production

如何在使用 Webjobs 时读取文件?

尝试这样做:

using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/content/file/file.txt")))
            {
                template = sr.ReadToEnd();
            }

但是运行本地失败

根据您的描述,对于本地:

我们可以使用以下代码获取 WebJob 项目根路径。

rootPath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()));

对于 Azure:

D:\home 为我们共享,我们可以在此路径中读取或写入文件。有关主目录访问的更多详细信息,请参阅 document. File structure on Azure please refer to another document. We also could browse it from Kudu (http://yourwebsite.scm.azurewebsites.net/) 工具。

As a convenience for our customers, the sandbox implements a dynamic symbolic link in kernel mode which maps d:\home to the customer home directory. This is done to remove the need of the customer to keep referencing their own network share path when accessing the site. No matter where the site runs, or how many sites run on a VM, each can access their home directory using

 rootPath = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot"

如果没有环境变量"Home"我们可以使用下面的代码来做到这一点。

 string path;
 if (Environment.GetEnvironmentVariable("HOME")!=null)
 {
     path = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot" + @"\testfilename.txt"; 
 }
 else
 {
    path = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + @"\testfilename.txt";
  }

详细测试步骤如下:

1.Create一个WebJob项目和test.text项目中的文件和文件夹测试

2.As 我在 WebJob 中使用定时器触发器,所以我需要在 program.cs

中添加 config.UseTimers()

3。在 Function.cs 文件中添加以下代码

public static void ProcessQueueMessage([TimerTrigger("00:00:03")] TimerInfo timerInfo, TextWriter log)
        {
            string instance = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID");
            string newMsg = $"WEBSITE_INSTANCE_ID:{instance}, timestamp:{DateTime.Now}";
            string path;
            if (Environment.GetEnvironmentVariable("HOME")!=null)
            {
                path = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot" + @"\test.txt"; 
            }
            else
            {
                path = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + @"\test.txt";
            }
            string template = File.ReadAllText(path);
            log.WriteLine($"NewMsge: {newMsg},file Content:{template}");
            Console.WriteLine($"NewMsge: {newMsg},file Content:{template}");
        }

4.Test 在本地机器上。

5.After 部署到 Azure 并从 Azure WebJob 仪表板获取日志。

6.After 部署到 Azure 并从 Azure WebJob 仪表板获取日志。