gpt4 book ai didi

linux - CallerFilePathAttribute 在 Azure 的 Linux 容器应用程序服务上不返回具有有效目录分隔符的文件路径

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:39 24 4
gpt4 key购买 nike

我在 netcore2.1 网络应用程序中有以下方法:

public static void Information(string message, [CallerFilePath] string filePath = "")
{
var fileNameWithoutExtn = Path.GetFileNameWithoutExtension(filePath);
. . .
}

在 Azure 应用程序服务(Windows 主机)上运行时,它的行为符合预期:

filePath =C:\web\src\production\MyWebsite\Controllers\ChallengeController.cs

fileNameWithoutExtn = ChallengeController



但是,当我在 azure 的 linux 容器应用服务上运行它时:

filePath =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 forum 中发布了相同的内容但没有得到任何回应,因此张贴在这里。如果我在那里听到,我会在这里更新。

最佳答案

这是因为:

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;
}`

关于linux - CallerFilePathAttribute 在 Azure 的 Linux 容器应用程序服务上不返回具有有效目录分隔符的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com