Assembly :: GetExecutingAssembly() - >位置现在抛出ArgumentException:路径中的非法字符

时间:2016-09-01 05:51:57

标签: .net node.js visual-studio-2015 c++-cli

在Visual Studio 2010(和.Net 4)中的node.js本机插件中,我可以使用

System::Reflection::Assembly::GetExecutingAssembly()->Location

获取正在运行的C ++ / CLI程序集的路径,但在Visual Studio 2015项目(和.Net 4.6)中的node.js插件中,我得到一个例外:

System.ArgumentException: Illegal characters in path.
   at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
   at System.Security.Permissions.FileIOPermission.CheckIllegalCharacters(
      String[] str)
   at System.Security.Permissions.FileIOPermission.AddPathList(
      FileIOPermissionAccess access, AccessControlActions control,
      String[] pathListOrig, Boolean checkForDuplicates,
      Boolean needFullPath, Boolean copyPathList)
   at System.Security.Permissions.FileIOPermission..ctor(
      FileIOPermissionAccess access, String path)
   at System.Reflection.RuntimeAssembly.get_Location()

知道如何获取正在运行的程序集的路径吗?

编辑2018-01-25 Visual Studio 2017仍未解决此问题,这次尝试使用.Net 4.5.2

1 个答案:

答案 0 :(得分:0)

尽管会抛出Location属性,但仍可以使用CodeBase,它返回的内容如下:

file://?/C:/.../my-addon.node

这将解释非法字符:“?”

一个new Uri(Application.CodeBase).LocalPath将返回

/?/C:/.../my-addon.node

因此,GetExecutingAssembly()->Location的解决方法可能是:

String^ GetExecutingAssemblyLocation()
{
  try
  {
    return Path::GetDirectoryName(Assembly::GetExecutingAssembly()->Location);
  }
  catch (Exception^ e)
  {
    String^ codeBase = Assembly::GetExecutingAssembly()->CodeBase;
    if (codeBase->StartsWith("file://?/"))
    {
      Uri^ codeBaseUri = gcnew Uri("file://" + codeBase->Substring(8));
      return codeBaseUri->LocalPath;
    }
    else
      throw;
  }
}

这将返回

C:\...\my-addon.node