Azure 和 File.CreateText : FileNotFoundException: Could not find file

标签 azure asp.net-core createfile

我有一个简单的 .Net Core MVC Web 应用程序,已部署到 Azure。在应用程序中,我使用 File.CreateText() 创建一个名为“test.txt”的小文本文件。这在我的本地 PC 上运行良好,但是当我将其部署到 Azure 时,我收到一条奇怪的消息:“找不到文件 'D:\home\site\wwwroot\wwwroot\test.txt'。”

确实,该文件不存在——这就是我创建它的原因。另外,SO 上的其他人似乎也遇到了类似的问题:FileNotFoundException when using System.IO.Directory.CreateDirectory()

我没有写权限吗?为什么 Azure 不允许我创建该文件?

代码(在 Startup.cs 中):

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
    using (var sw = File.CreateText(env.WebRootPath + "/test.txt")) { }
}

错误屏幕截图:

enter image description here

最佳答案

我在发布此问题后不久就找到了此错误的原因,但忘记发布答案:

事实证明,当您部署到 Azure 时,您的站点从临时目录运行,该目录在每次部署时都会被删除并重新创建。因此,Azure 会禁止在应用程序目录中创建和编辑文件,因为它们将在下次部署时被删除(如果 Azure 显示的错误消息能提供更多信息,那就太好了)。

因此,在 Azure 应用程序上创建和编辑文件并使它们在部署中保留的方法是使用以下方法之一:

  1. 数据库 BLOB 存储(只需将文件作为字节数组存储在数据库中。如果您已经在使用数据库,则无需花费任何费用)
  2. Azure BLOB 存储(将您的文件存储到 Azure 上的特殊云中。需要付费)

发布这个问题后不久,我在某个网站上读到了这篇文章,但我不记得在哪里,所以我为没有来源而道歉。

关于Azure 和 File.CreateText : FileNotFoundException: Could not find file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57117675/

相关文章:

python - 想要生成 databricks 笔记本 URL 来发送警报

azure - 删除 AD b2c 目录

适用于 Linux 的 Azure 扩展脚本

c# - LinkGenerator 返回 NULL Url 而 Url.Action 不...为什么

azure - 缓存与 Azure Blob 存储的连接

c# - 无效的受众 token 验证

c# - 在 WPF 自托管 asp.net 核心应用程序中加载 View

c - 窗口 c : failed to create mmap of a file

vba - 如何创建文件名中包含特殊字符的文本文件