How do I get the path of the assembly the code is in?

前端 未结 30 2827
小蘑菇
小蘑菇 2020-11-21 16:17

Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code.

<
30条回答
  •  遥遥无期
    2020-11-21 16:54

    As far as I can tell, most of the other answers have a few problems.

    The correct way to do this for a disk-based (as opposed to web-based), non-GACed assembly is to use the currently executing assembly's CodeBase property.

    This returns a URL (file://). Instead of messing around with string manipulation or UnescapeDataString, this can be converted with minimal fuss by leveraging the LocalPath property of Uri.

    var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
    var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
    var directoryPath = Path.GetDirectoryName(filePathToCodeBase);
    

提交回复
热议问题