如何获取执行中的.exe的名称?
时间:2020-03-05 18:42:47 来源:igfitidea点击:
压缩框架不支持Assembly.GetEntryAssembly来确定启动的.exe。因此,还有另一种方法来获取执行中的.exe的名称吗?
编辑:我在彼得·福特的博客上找到了答案:http://peterfoot.net/default.aspx
这是代码:
byte[] buffer = new byte[MAX_PATH * 2]; int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH); if (chars > 0) { string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2); } [DllImport("coredll.dll", SetLastError = true)] private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
解决方案
回答
我不确定它是否可以从托管代码(甚至紧凑的框架)运行,但是在Win32中,我们可以调用GetModuleFileName来查找正在运行的exe文件。
MSDN:GetModuleFileName
回答
在托管代码中,我认为我们可以使用以下代码:
http://msdn.microsoft.com/zh-CN/library/system.windows.forms.application.executablepath.aspx
Application.ExecutablePath
回答
string exefile = Assembly.GetExecutingAssembly().GetName().CodeBase;
但是,如果将其放在DLL程序集中,我相信它将为我们提供程序集文件名。
对"完全"框架的相同调用将返回带有" file:"前缀的.exe文件。