c# - 获取 Azure WebApp 上的 ASP.NET 类库项目中的文件路径

标签 c# azure asp.net-core azure-web-app-service

我有一个类库,在其中我可以使用以下代码从应用程序路径访问文件。它不适用于 azure ,因为它找不到应用程序路径。如何让它在我的本地计算机上正常工作,从而使其正常工作。

 private string GetProjectPath()
        {
            string SolutionName = "MyApi.sln";
            //Get name of the target project which we want to test

            var projectName = typeof(TerminationMatchInquiry).GetTypeInfo().Assembly.GetName().Name;

            //Get currently executing test project path
            var applicationBasePath = new Uri((typeof(TerminationMatchInquiry).GetTypeInfo().Assembly.CodeBase)).LocalPath;
            //Find the folder which contains the solution file. We then use this information to find the 
            //target project which we want to test
            DirectoryInfo directoryInfo = new DirectoryInfo(applicationBasePath);
            do
            {
                var solutionFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, SolutionName));
                if (solutionFileInfo.Exists)
                {
                    return Path.GetFullPath(Path.Combine(directoryInfo.FullName, projectName));
                }
                directoryInfo = directoryInfo.Parent;
            }
            while (directoryInfo.Parent != null);

            throw new Exception($"Solution root could not be located using application root {applicationBasePath}");
        }

最佳答案

要获取网络应用程序上的准确文件路径,您可能需要进行反复试验。

下面的代码是我在 ASP.NET 项目中使用的代码。假设您有一个名为 scenarios 的文件夹和filename变量;

string rootPath;
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HOME")))
    rootPath = Environment.GetEnvironmentVariable("HOME") + "\\site\\wwwroot\\bin";
else if (HttpContext.Current != null)
    rootPath = HttpContext.Current.Server.MapPath("~");
else
    rootPath = ".";
string path = rootPath + "\\scenarios\\" + filename;

让我们看看每个条件的值;

  1. Environment.GetEnvironmentVariable("HOME") :此值适用于 Azure WebApp。 Azure WebApp具有主机根目录的默认环境变量。您可以检查提供的变量 here

  2. HttpContext.Current :当您在桌面上开发时,此值适用于带有 OWIN selfhost 的 iisexpress。

  3. rootPath = ".";该值适用于经典 IIS。

因此,查找已发布文件路径的最佳快捷方式可能是,

  1. 查看您的文件是否已在 WebApp 上良好部署。您可以通过WebApp > Advanced Tools (a.k.a Kudu) menu > Debug Console menu on top > CMD查看已发布的文件。它将在浏览器上向您显示类似资源管理器的界面。
  2. 尝试使用如下文件路径写入日志; Environment.GetEnvironmentVariable("HOME") + "\\site\\wwwroot\\bin\\" + yourdirectory + "\\" + SolutionName并检查那里的文件是否加载成功。

关于c# - 获取 Azure WebApp 上的 ASP.NET 类库项目中的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642622/

相关文章:

azure - 有两种方法可以从 azure 函数 HTTP 触发器读取所有服务总线消息

asp.net-core - Asp.Net Core Identity - 使用角色和缓存授权属性?

c# - Asp.Net Core 2 验证不记名 token

c# - 试图使用 Crypto 混淆我的项目破坏了它

azure - 如何自动创建具有媒体基础功能的Azure云服务?

c# - C 代码模拟器的 GUI 和后端选择

azure - 从 Azure DevOps 发布到 Azure 应用服务 : "You do not have permission to view this directory or page"

asp.net-core - ASP.Net Core 本地化

c# - 如何将 WPF MouseDevice.GetPosition(null) 转换为屏幕坐标?

c# - 如何捕获 ClearScript.V8 中的更新事件?