【问题标题】:getting file path in asp.net class library project on Azure WebApp在 Azure WebApp 上的 asp.net 类库项目中获取文件路径
【发布时间】:2017-06-20 02:00:53
【问题描述】:

我有一个类库,我可以在其中使用以下代码从应用程序路径访问文件。它无法在 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}");
        }

【问题讨论】:

  • 你的意思是 Azure WebApp?
  • 是 Azure WebApp
  • 当然在 azure 上找不到!当您部署应用程序时,您不部署源代码只是由构建/发布过程创建的二进制工件

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


【解决方案1】:

要在您的 web 应用上获取准确的文件路径,您可能需要反复试验。

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

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 并检查那里的文件加载成功。

【讨论】:

  • @maxspan // Environment.GetEnvironmentVariable 也适用于核心。首先尝试一下 :) HttpContext.Current 有替代方案,因为此链接描述了 stackoverflow.com/questions/38571032/… 您可以省略检查此值,因为您的开发设置工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多