我想要获得当前运行程序的名称,即程序的可执行名称。在C/ c++中,你从args[0]中得到它。
当前回答
当你不确定或有疑问时,绕着圈子跑,尖叫和大喊。
class Ourself
{
public static string OurFileName() {
System.Reflection.Assembly _objParentAssembly;
if (System.Reflection.Assembly.GetEntryAssembly() == null)
_objParentAssembly = System.Reflection.Assembly.GetCallingAssembly();
else
_objParentAssembly = System.Reflection.Assembly.GetEntryAssembly();
if (_objParentAssembly.CodeBase.StartsWith("http://"))
throw new System.IO.IOException("Deployed from URL");
if (System.IO.File.Exists(_objParentAssembly.Location))
return _objParentAssembly.Location;
if (System.IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
if (System.IO.File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location))
return System.Reflection.Assembly.GetExecutingAssembly().Location;
throw new System.IO.IOException("Assembly not found");
}
}
我不能声称已经测试了每个选项,但它不会做任何愚蠢的事情,比如在调试会话期间返回vhost。
其他回答
您可以使用Environment. getcommandlineargs()来获取参数和Environment. getcommandlineargs()。CommandLine获取实际输入的命令行。
此外,您可以使用Assembly.GetEntryAssembly()或Process.GetCurrentProcess()。
但是,在调试时,您应该小心,因为最后一个示例可能会给出调试器的可执行文件名称(取决于您如何附加调试器),而不是可执行文件,其他示例可能也是如此。
如果您需要程序名称来设置防火墙规则,请使用:
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
这将确保在VisualStudio中调试和在windows中直接运行应用程序时名称是正确的。
System.Diagnostics.Process.GetCurrentProcess()获取当前正在运行的进程。您可以使用ProcessName属性来确定名称。下面是一个示例控制台应用程序。
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Process.GetCurrentProcess().ProcessName);
Console.ReadLine();
}
}
System.AppDomain.CurrentDomain.FriendlyName -返回带扩展名的文件名(例如MyApp.exe)。
System.Diagnostics.Process.GetCurrentProcess()。ProcessName -返回没有扩展名的文件名(例如MyApp)。
.MainModule System.Diagnostics.Process.GetCurrentProcess()。FileName -返回完整的路径和文件名(例如C:\Examples\Processes\MyApp.exe)。然后,您可以将此传递到System.IO.Path.GetFileName()或System.IO.Path.GetFileNameWithoutExtension()以实现与上述相同的结果。
如果你正在寻找可执行文件的完整路径信息,可靠的方法是使用以下方法:
var executable = System.Diagnostics.Process.GetCurrentProcess().MainModule
.FileName.Replace(".vshost", "");
这消除了中间dll、vshost等的任何问题。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何从终端/命令行调用VS代码编辑器
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 在Jar文件中运行类
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 如何在Windows命令提示符下运行.sh ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?