• .NET CF获取当前dll及其调用程序的文件名和完全路径



      在dll中有时需要使用主调用程序中的资源,这就要正确获取调用程序的文件名及其路径等信息。这需要和调用dll本身的文件名和路径区分开来!

        这就牵扯到System.Reflection.Assembly程序集类使用了。

         GetExecutingAssembly : 获取包含当前执行的代码的程序集

         GetCallingAssembly : 返回调用当前正在执行的方法的方法的 System.Reflection.Assembly 

        下面为某个dll中的静态函数,注意区别:

    1. public static void GetName()
    2. {
    3.     // 当前dll相关程序集名
    4.     Debug.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().GetName().CodeBase));
    5.     Debug.WriteLine(Assembly.GetExecutingAssembly().GetModules()[0].Name);
    6.     Debug.WriteLine(Assembly.GetExecutingAssembly().ManifestModule.Name);
    7.     Debug.WriteLine("");
    8.     Debug.WriteLine(Assembly.GetExecutingAssembly().GetName().CodeBase);
    9.     Debug.WriteLine(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
    10.     Debug.WriteLine(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
    11.     Debug.WriteLine("");
    12.  
    13.     // 调用程序的相关程序集名称
    14.     Debug.WriteLine(Path.GetFileName(Assembly.GetCallingAssembly().GetName().CodeBase));
    15.     Debug.WriteLine(Assembly.GetCallingAssembly().GetModules()[0].Name);
    16.     Debug.WriteLine(Assembly.GetCallingAssembly().ManifestModule.Name);
    17.     Debug.WriteLine("");
    18.     Debug.WriteLine(Assembly.GetCallingAssembly().GetName().CodeBase);
    19.     Debug.WriteLine(Assembly.GetCallingAssembly().GetModules()[0].FullyQualifiedName);
    20.     Debug.WriteLine(Assembly.GetCallingAssembly().ManifestModule.FullyQualifiedName);
    21. }

        上面的静态函数在TestClass类中,然后在调用程序中调用该静态函数,调用程序为“GetApplicationName.exe”,如下:

    1. TestClass.GetName();

        观察结果,如下: 

    1. TestDll.dll
    2. TestDll.dll
    3. TestDll.dll
    4.  
    5. \Program Files\GetApplicationName\TestDll.dll
    6. \Program Files\GetApplicationName\TestDll.dll
    7. \Program Files\GetApplicationName\TestDll.dll
    8.  
    9. GetApplicationName.exe
    10. GetApplicationName.exe
    11. GetApplicationName.exe
    12.  
    13. \Program Files\GetApplicationName\GetApplicationName.exe
    14. \Program Files\GetApplicationName\GetApplicationName.exe
    15. \Program Files\GetApplicationName\GetApplicationName.exe

      还有一个办法,但是只能获取调用程序的文件名,不能获取完全路径,那就是通过AppDomain.CurrentDomain.FriendlyName获取,如下:

    1. Debug.WriteLine(AppDomain.CurrentDomain.FriendlyName);

        结果:

    1. GetApplicationName.exe

        

        你还可以参考这篇文章: 为Windows mobile编写设计友好的控件,里面也对AppDomain.CurrentDomain.FriendlyName做了介绍。

    代码下载:

     GetApplicationName.rar

     
  • 相关阅读:
    【Go学习笔记】 string转Map 和 Map嵌套取值 和 interface转string
    【Go 学习】Go 正则类似Python findall()方法
    【Go学习】Go mod 包管理
    构建之法阅读笔记(四)
    nltk安装配置以及语料库的安装配置
    机器学习KNN算法实现新闻文本分类思路总结
    KNN算法源代码
    构建之法阅读笔记(三)
    jupyter反爬虫
    python多条件模糊查询
  • 原文地址:https://www.cnblogs.com/Lisen/p/1631446.html
Copyright © 2020-2023  润新知