【问题标题】:Getting name of the current executable from assembly vs process?从程序集与进程中获取当前可执行文件的名称?
【发布时间】:2012-01-14 10:57:14
【问题描述】:

这是对this answer 的跟进(它是 cmets)。从程序集与进程获取可执行文件名称有什么区别?

System.Reflection.Assembly.GetCallingAssembly.GetEntryAssembly().CodeBase 

对比

Process.GetCurrentProcess().ProcessName

我假设这些将一直相同?不?有优点和缺点吗?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    它们不一定相同。将这两个程序编译为控制台应用程序在同一目录下:

    // In Test.cs, compile to Test.exe
    using System;
    using System.Reflection;
    
    public static class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CreateDomain("NewDomain").ExecuteAssembly("Test2.exe");
        }
    }
    
    // In Test2.cs, compile to Test2.exe
    using System;
    using System.Diagnostics;
    using System.Reflection;
    
    class Test2
    {
        static void Main()
        {
            Console.WriteLine("Process: {0}",
                              Process.GetCurrentProcess().ProcessName);
            Console.WriteLine("Entry assembly: {0}", 
                              Assembly.GetEntryAssembly().CodeBase);
        }
    }
    

    输出:

    Process: Test
    Entry assembly: file:///c:/Users/Jon/Test/Test2.EXE
    

    【讨论】:

      【解决方案2】:

      ProcessName 是操作系统主机进程的名称。

      Assembly CodeBase 指向给定进程内的程序集。同一个程序集可以由不同的进程托管。

      【讨论】:

        【解决方案3】:

        不,它们不需要返回相同的值。

        碰巧,我最近遇到了这个“陷阱”:它们可以返回不同的值,具体取决于您是直接运行 .exe 还是从 MSVS 调试器内部运行:

        How do I get the .exe name of a C# console application?

        这只是一个例子 - 我相信可能还有其他例子。

        '希望有帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-24
          • 2011-11-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-19
          相关资源
          最近更新 更多