linux - CallerFilePathAttribute 未在 azure 的 linux 容器应用服务上返回具有有效目录分隔符的文件路径
问题描述
我在 netcore2.1 网络应用程序中有以下方法:
public static void Information(string message, [CallerFilePath] string filePath = "")
{
var fileNameWithoutExtn = Path.GetFileNameWithoutExtension(filePath);
. . .
}
在 azure app 服务(windows 主机)上运行时,它的行为符合预期:
文件路径 = C:\web\src\production\MyWebsite\Controllers\ChallengeController.cs
fileNameWithoutExtn = ChallengeController
但是,当我在 azure 的 linux 容器应用服务上运行它时:
文件路径 = C:\web\src\production\MyWebsite\Controllers\ChallengeController.cs
fileNameWithoutExtn = C:\web\src\production\MyWebsite\Controllers\ChallengeController
和
Path.DirectorySeparatorChar = /
Path.AltDirectorySeparatorChar = /
Path.PathSeparator =:
Path.VolumeSeparatorChar = /
为什么 CallerFilePath 给我的路径与 DirectorySeparatorChar 或 AltDirectorySeparatorChar 不匹配?
PS:我在msdn论坛发了同样的帖子,但没有得到任何回应,所以在这里发帖。如果我在那里听到,我会在这里更新。
解决方案
这是因为:
a) Linux 使用 '\' 作为目录分隔符,而 Windows 使用 '/'
b) CallerFilePath 在编译时返回路径。该代码是在 Windows 上编译的,而不是在 Linux 上编译的。
所以你得到filePath = C:\web\src\production\MyWebsite\Controllers\ChallengeController.cs
解决方法是编写自己的方法来获取文件名,例如:
static void Main(string[] args)
{
char DirectorySeparatorChar='\\';
string path = @"C:\web\src\production\MyWebsite\Controllers\ChallengeController.cs";
string fileName = GetFileNameWithoutExtension(path, DirectorySeparatorChar);
}
public static String GetFileName(String path,char DirectorySeparatorChar)
{
if (path != null)
{
int length = path.Length;
for (int i = length; --i >= 0;)
{
char ch = path[i];
if (ch == DirectorySeparatorChar )
return path.Substring(i + 1, length - i - 1);
}
}
return path;
}
public static String GetFileNameWithoutExtension(String path, char DirectorySeparatorChar)
{
path = GetFileName(path, DirectorySeparatorChar);
if (path != null)
{
int i;
if ((i = path.LastIndexOf('.')) == -1)
return path;
else
return path.Substring(0, i);
}
return null;
}`
推荐阅读
- python-3.x - 数据帧条目中一列与其他列的比较以提高数据质量
- android-studio - 修复警告:jks 密钥库使用专有格式。建议迁移到pkcs12
- ruby-on-rails - 多类别模型与具有 STI 的单类别模型?- 导轨
- google-cloud-platform - 仅使用 JSON API 检索 Google Cloud 对象的元数据?
- svg - SVG - 带有背景颜色和圆角边框的文本
- python - 如何使用 CodeHS 8.4.13: Owls, Part 2 的枚举函数?
- bash - 逐行应用字符串替换
- angular - NGRX 过滤器导致 ExpressionChangedAfterItHasBeenCheckedError
- javascript - javascript中未填写字段时如何显示错误消息?
- ruby - 总是在“捆绑执行”之前“捆绑安装”?