Server.MapPath 在 Azure 上找不到路径

Server.MapPath does not find the path on Azure

我已经将我的项目部署到 Azure。在我的项目中,我有 "App_Data\Images" 个文件夹。

现在我正在尝试执行以下操作:

String filename = GLOBAL_IMAGES_VALS.GET_FILE_PREFIX(imageType) + "-" + User.Identity.GetUserId<int>().ToString() + Path.GetExtension(image.FileName);

String origPath = Server.MapPath("~\App_Data")+"\Images\"  + filename;

但是在尝试之后:

image.SaveAs(origPath);

我收到此错误消息:

Could not find a part of the path 'D:\home\site\wwwroot\App_Data\Images\logo-10003065.jpg'.

如何将我的文件保存到 "App_Data\Images\"

也许是这样:

System.Web.Hosting.HostingEnvironment.MapPath("~\App_Data")+"\Images\"  + filename )

可能images文件夹不存在需要先创建?如果它是为上传图片的人设计的,我不建议像这样在您的应用中保存图片。我会通过 blob 或新的 Azure 文件存储将它们保存在 Azure 存储中。我会保持你的应用程序部署文件干净,只与你的应用程序相关,并将用户生成的任何内容保存在它之外。

顺便说一句,如果您使用的是 Azure Web Apps,您可以使用 "HOME" 的环境变量来始终获得正确的路径(应该是 D:\home)

string path = Environment.GetEnvironmentVariable("HOME") +
                           "\site\wwwroot\App_Data\images"

我假设您的 AppData 文件夹就在 wwwroot 文件夹下,这通常是这种情况。

试试这个:

HttpContext.Current.Server.MapPath(Path.Combine("~/AppData/Images/", filename));

实际问题是子文件夹'Images'不存在。我不记得为什么发布过程没有创建这个子文件夹,但是我手动添加了它,然后一切正常。

编辑:

正如其他人在这里写的那样 (@Spectarion)。我将在此处添加重要说明以解释未创建文件夹的原因:

Just for the future readers, folder won't be created if it's empty. Folder is empty even if there are files that are not included in project.

只需将一些 'fake.txt' 文件放入您想要创建的任何文件夹中,当然不要忘记将其添加到项目中。祝你好运。

由于特定文件夹中没有任何文件,因此在发布 Web 部署时会忽略空文件夹。

快速修复:在发布前将任何文件添加到文件夹将解决此问题。

我刚刚在 VS15 上遇到了这个问题。我首先遵循 this question 中的建议以生成您遇到的错误。我猜这部分遵循 dsb 的回答,但 dsb 没有给出任何修复此问题的实际过程的描述。

然后去https://<mywebsite>.scm.azurewebsites.net/DebugConsole翻目录,发现App_Data还没有发表

这就是抛出错误的原因。所以,然后我通过简单地转到解决方案资源管理器解决了这个问题,右键单击 App_Data 并选择 "Publish App_Data".

但是,我的网站是一个项目的短期学术成果 - 我认为考虑 上面关于是否允许用户上传到部署的回答可能有很多话要说地区是个好主意

if (!Directory.Exists(Server.MapPath("~/Images")))
{                
      Directory.CreateDirectory(Server.MapPath("~/Images"));
}

文件夹中可能缺少该目录。创建目录并在文件路径中使用它