从汇编代码和进程中获取当前可执行文件的名称有什么区别?

3
这是对这个答案及其评论的跟进。从程序集和进程中获取可执行文件名有什么区别?
System.Reflection.Assembly.GetCallingAssembly.GetEntryAssembly().CodeBase 

vs

Process.GetCurrentProcess().ProcessName

我假设这些会一直保持不变?不是吗?有什么优缺点吗?
3个回答

6
它们并不一定相同。将这两个程序编译为控制台应用程序,放在同一个目录中:
// 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

4

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

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


3

不需要返回相同的值。

最近我遇到了一个“陷阱”:它们可以根据您是直接运行 .exe 还是从 MSVS 调试器中运行而返回不同的值:

如何获取 C# 控制台应用程序的 .exe 名称?

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

希望这能有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接