使用 Webjobs 时如何读取文件?
试图这样做:
using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/content/file/file.txt")))
{
template = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
但是在本地运行失败
根据您的描述,对于本地:
我们可以使用以下代码来获取 WebJob 项目根路径。
rootPath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()));
Run Code Online (Sandbox Code Playgroud)
对于 Azure:
D:\home为我们共享,我们可以在此路径中读取或写入文件。有关主目录访问的更多详细信息,请参阅文档。Azure 上的文件结构请参阅另一个文档。我们也可以从 Kudu ( http://yourwebsite.scm.azurewebsites.net/ ) 工具浏览它。
为了方便我们的客户,沙箱在内核模式下实现了一个动态符号链接,将 d:\home 映射到客户主目录。这样做是为了消除客户在访问站点时继续引用他们自己的网络共享路径的需要。无论站点在哪里运行,或者在 VM 上运行多少个站点,每个站点都可以使用
rootPath = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot"
Run Code Online (Sandbox Code Playgroud)
如果没有环境变量“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";
}
Run Code Online (Sandbox Code Playgroud)
以下是详细的测试步骤:
1.创建一个WebJob项目和项目中的test.text文件和文件夹test
2.由于我在 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}");
}
Run Code Online (Sandbox Code Playgroud)
4.在本地机器上测试。
5.部署到Azure后,从Azure WebJob仪表板获取日志。
6.部署到Azure后,从Azure WebJob仪表板获取日志。