How can I get the application's path in a .NET

2018-12-31 02:07发布

How do I find the application's path in a console application?

In Windows Forms, I can use Application.StartupPath to find the current path, but this doesn't seem to be available in a console application.

26条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 02:59

There are many ways to get executable path, which one we should use it depends on our needs here is a link which discuss different methods.

Different ways to get Application Executable Path

查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 03:00

If you are looking for a .NET Core compatible way, use

System.AppContext.BaseDirectory

This was introduced in .NET Framework 4.6 and .NET Core 1.0 (and .NET Standard 1.3). See: AppContext.BaseDirectory Property.

According to this page,

This is the prefered replacement for AppDomain.CurrentDomain.BaseDirectory in .NET Core

查看更多
几人难应
4楼-- · 2018-12-31 03:01

you can use this one instead.

System.Environment.CurrentDirectory
查看更多
梦该遗忘
5楼-- · 2018-12-31 03:03

I have used this code and get the solution.

AppDomain.CurrentDomain.BaseDirectory
查看更多
回忆,回不去的记忆
6楼-- · 2018-12-31 03:04

You can simply add to your project references System.Windows.Forms and then use the System.Windows.Forms.Application.StartupPath as usual .

So, not need for more complicated methods or using the reflection.

查看更多
刘海飞了
7楼-- · 2018-12-31 03:06

System.Reflection.Assembly.GetExecutingAssembly().Location1

Combine that with System.IO.Path.GetDirectoryName if all you want is the directory.

1As per Mr.Mindor's comment:
System.Reflection.Assembly.GetExecutingAssembly().Location returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory. System.Reflection.Assembly.GetExecutingAssembly().CodeBase will return the 'permanent' path of the assembly.

查看更多
登录 后发表回答