首页 > 解决方案 > 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论坛发了同样的帖子,但没有得到任何回应,所以在这里发帖。如果我在那里听到,我会在这里更新。

标签: linuxazureazure-web-app-service

解决方案


这是因为:

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

推荐阅读