我有一个类库,在其中我可以使用以下代码从应用程序路径访问文件。它不适用于 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;
让我们看看每个条件的值;
Environment.GetEnvironmentVariable("HOME")
:此值适用于 Azure WebApp。 Azure WebApp具有主机根目录的默认环境变量。您可以检查提供的变量 hereHttpContext.Current
:当您在桌面上开发时,此值适用于带有 OWIN selfhost 的 iisexpress。rootPath = ".";
该值适用于经典 IIS。
因此,查找已发布文件路径的最佳快捷方式可能是,
- 查看您的文件是否已在 WebApp 上良好部署。您可以通过
WebApp > Advanced Tools (a.k.a Kudu) menu > Debug Console menu on top > CMD
查看已发布的文件。它将在浏览器上向您显示类似资源管理器的界面。 - 尝试使用如下文件路径写入日志;
Environment.GetEnvironmentVariable("HOME") + "\\site\\wwwroot\\bin\\" + yourdirectory + "\\" + SolutionName
并检查那里的文件是否加载成功。
关于c# - 获取 Azure WebApp 上的 ASP.NET 类库项目中的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642622/