我想要获得当前运行程序的名称,即程序的可执行名称。在C/ c++中,你从args[0]中得到它。
当前回答
试试这个:
System.Reflection.Assembly.GetExecutingAssembly()
这将返回一个System.Reflection.Assembly实例,其中包含您希望了解的有关当前应用程序的所有数据。我认为Location属性可能会得到你想要的。
其他回答
如果您需要程序名称来设置防火墙规则,请使用:
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
这将确保在VisualStudio中调试和在windows中直接运行应用程序时名称是正确的。
在。net Core(或Mono)上,当定义进程的二进制文件是Mono或。net Core (dotnet)的运行时二进制文件,而不是您感兴趣的实际应用程序时,大多数答案都不适用。在这种情况下,使用这个:
var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);
对于windows应用程序(窗体和控制台),我使用这个:
在VS中添加对System.Windows.Forms的引用,然后:
using System.Windows.Forms;
namespace whatever
{
class Program
{
static string ApplicationName = Application.ProductName.ToString();
static void Main(string[] args)
{
........
}
}
}
无论我是运行实际的可执行文件还是在VS中调试,这对我来说都是正确的。
注意,它返回的是应用程序名称,而不是扩展名。
John
试试这个:
System.Reflection.Assembly.GetExecutingAssembly()
这将返回一个System.Reflection.Assembly实例,其中包含您希望了解的有关当前应用程序的所有数据。我认为Location属性可能会得到你想要的。
当你不确定或有疑问时,绕着圈子跑,尖叫和大喊。
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。
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- 使iTerm以与其他操作系统相同的方式翻译“元键”
- 为什么我不能在c#中有抽象静态方法?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?