如何在.NET控制台应用程序中获取应用程序的路径?

时间:2022-10-01 20:47:37

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.

在Windows窗体中,我可以使用Application。StartupPath去查找当前路径,但是在控制台应用程序中这似乎不可用。

25 个解决方案

#1


1019  

System.Reflection.Assembly.GetExecutingAssembly().Location1

.Location1 System.Reflection.Assembly.GetExecutingAssembly()

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

将其与System.IO.Path结合。如果您想要的是目录,那么GetDirectoryName。

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.

根据Mr.Mindor的评论:System.Reflection.Assembly.GetExecutingAssembly()Location返回当前执行程序集所在的位置,该位置可能在不执行时也可能不在程序集所在的位置。对于影子复制程序集,您将在临时目录中获得一条路径。System.Reflection.Assembly.GetExecutingAssembly()。代码库将返回程序集的“永久”路径。

#2


355  

You can use the following code to get the current application directory.

可以使用以下代码获取当前应用程序目录。

AppDomain.CurrentDomain.BaseDirectory

#3


116  

You have two options for finding the directory of the application, which you chose will depend on your purpose.

您有两个选项可以找到应用程序的目录,您选择的目录将取决于您的目的。

// to get the location the assembly is executing from
//(not necessarily where the it normally resides on disk)
// in the case of the using shadow copies, for instance in NUnit tests, 
// this will be in a temp directory.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;

//To get the location the assembly normally resides on disk or the install directory
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

//once you have the path you get the directory with:
var directory = System.IO.Path.GetDirectoryName(path);

#4


72  

Probably a bit late but this is worth a mention:

可能有点晚了,但值得一提:

Environment.GetCommandLineArgs()[0];

Or more correctly to get just the directory path:

或更准确地获取目录路径:

System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

Edit:

编辑:

Quite a few people have pointed out that GetCommandLineArgs is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.

很多人指出GetCommandLineArgs不能保证返回程序名。在命令行上看到的第一个单词是程序名,它只是按惯例命名的。这篇文章确实指出,“尽管使用这种怪癖的Windows程序非常少(我自己也不知道)”。因此,“欺骗”getlineargs是可能的,但我们讨论的是控制台应用程序。控制台应用程序通常又快又脏。这与我的吻哲学相吻合。

#5


36  

For anyone interested in asp.net web apps. Here are my results of 3 different methods

对于任何对asp.net web应用程序感兴趣的人。以下是我用三种不同方法得出的结果

protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}

result

结果

p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging

the app is physically running from "C:\inetpub\SBSPortal_staging", so the first solution is definitely not appropriate for web apps.

这个应用程序在物理上运行于“C:\inetpub\SBSPortal_staging”,所以第一个解决方案肯定不适合web应用程序。

#6


34  

The answer above was 90% of what I needed, but returned a Uri instead of a regular path for me.

上面的答案是我所需的90%,但是返回一个Uri而不是常规路径。

As explained in the MSDN forums post, How to convert URI path to normal filepath?, I used the following:

如MSDN论坛文章中所解释的,如何将URI路径转换为普通的文件路径?,我使用以下资料:

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;

#7


26  

You may be looking to do this:

你可能想这样做:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

#8


18  

you can use this one instead.

你可以用这个。

System.Environment.CurrentDirectory

#9


16  

For Console Applications, you can try this:

对于控制台应用程序,您可以尝试以下操作:

System.IO.Directory.GetCurrentDirectory();

Output (on my local machine):

输出(在本地机器上):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

c:\ \ xxxxxxx \用户文档\ visual studio 2012 \ \ ImageHandler \ GetDir \ bin \调试项目

Or you can try (there's an additional backslash in the end):

或者你也可以试试(最后还有一个反斜杠):

AppDomain.CurrentDomain.BaseDirectory

Output:

输出:

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

c:\ \ xxxxxxx \用户文档\ visual studio 2012 \ ImageHandler \ GetDir \ bin \ \项目调试\

#10


11  

I have used this code and get the solution.

我使用了这段代码并得到了解决方案。

AppDomain.CurrentDomain.BaseDirectory

#11


7  

I use this if the exe is supposed to be called by double clicking it

如果exe应该通过双击来调用,我就使用这个。

var thisPath = System.IO.Directory.GetCurrentDirectory();

#12


7  

I have used

我已经使用

System.AppDomain.CurrentDomain.BaseDirectory

when I want to find a path relative to an applications folder. This works for both ASP.Net and winform applications. It also does not require any reference to System.Web assemblies.

当我想查找与应用程序文件夹相关的路径时。这对ASP都有效。净和winform上应用。它也不需要任何对系统的引用。Web组件。

#13


7  

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

您可以简单地将其添加到项目引用系统。windows中。然后使用System.Windows.Forms.Application。StartupPath像往常一样。

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

因此,不需要更复杂的方法或使用反射。

#14


5  

I mean, why not a p/invoke method?

为什么不使用p/invoke方法呢?

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    public class AppInfo
    {
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
            private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
            private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
            public static string StartupPath
            {
                get
                {
                    StringBuilder stringBuilder = new StringBuilder(260);
                    GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
                    return Path.GetDirectoryName(stringBuilder.ToString());
                }
            }
    }

You would use it just like the Application.StartupPath:

你会像使用程序一样使用它。

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

#15


4  

Assembly.GetEntryAssembly().Location or Assembly.GetExecutingAssembly().Location

Assembly.GetEntryAssembly()。.Location位置或Assembly.GetExecutingAssembly()

Use in combination with System.IO.Path.GetDirectoryName() to get only the directory.

与System.IO.Path.GetDirectoryName()结合使用,只获取目录。

The paths from GetEntryAssembly() and GetExecutingAssembly() can be different, even though for most cases the directory will be the same.

GetEntryAssembly()和GetExecutingAssembly()的路径可以不同,尽管在大多数情况下,目录是相同的。

With GetEntryAssembly() you have to be aware that this can return null if the entry module is unmanaged (ie C++ or VB6 executable). In those cases it is possible to use GetModuleFileName from the Win32 API:

使用GetEntryAssembly(),您必须知道,如果入口模块不受管理(即c++或VB6可执行文件),则可以返回null。在这些情况下,可以使用Win32 API中的GetModuleFileName:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);

#16


4  

AppDomain.CurrentDomain.BaseDirectory

Will resolve the issue to refer the 3rd party reference files with installation packages.

将解决提交第三方参考文件与安装包的问题。

#17


3  

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

如果你正在寻找一种。net核心兼容的方式,使用

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.

这是在。net Framework 4.6和。net Core 1.0(和。net Standard 1.3)中引入的。看到:AppContext。BaseDirectory财产。

According to this page,

根据这个页面,

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

这是AppDomain.CurrentDomain的首选项。BaseDirectory在。net核心

#18


2  

None of these methods work in special cases like using a symbolic link to the exe, they will return the location of the link not the actual exe.

这些方法在特殊情况下都不起作用,比如使用符号链接到exe,它们将返回链接的位置,而不是实际的exe。

So can use QueryFullProcessImageName to get around that:

所以可以使用QueryFullProcessImageName来解决这个问题:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);

    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern IntPtr OpenProcess(
        UInt32 dwDesiredAccess,
        [MarshalAs(UnmanagedType.Bool)]
        Boolean bInheritHandle,
        Int32 dwProcessId
    );
}

public static class utils
{

    private const UInt32 PROCESS_QUERY_INFORMATION = 0x400;
    private const UInt32 PROCESS_VM_READ = 0x010;

    public static string getfolder()
    {
        Int32 pid = Process.GetCurrentProcess().Id;
        int capacity = 2000;
        StringBuilder sb = new StringBuilder(capacity);
        IntPtr proc;

        if ((proc = NativeMethods.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)) == IntPtr.Zero)
            return "";

        NativeMethods.QueryFullProcessImageName(proc, 0, sb, ref capacity);

        string fullPath = sb.ToString(0, capacity);

        return Path.GetDirectoryName(fullPath) + @"\";
    }
}

#19


2  

Try this simple line of code:

试试下面这行简单的代码:

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);

#20


2  

in VB.net

在VB.net

My.Application.Info.DirectoryPath

works for me (Application Type: Class Library). Not sure about C#... Returns the path w/o Filename as string

适合我(应用类型:类库)。不确定关于c#…返回路径w/o文件名作为字符串

#21


0  

I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.

我没有看到任何人将. net核心反射提供的LocalPath转换成可用的系统。IO路径,这是我的版本。

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;

}

This will return the full "C:\xxx\xxx" formatted path to where your code is.

这将返回完整的“C:\xxx\xxx”格式的路径到代码所在的位置。

#22


0  

Following line will give you an application path:

下面的代码将为您提供一个应用程序路径:

var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

Above solution is working properly in following situations:

上述解决方案在以下情况下工作正常:

  • simple app
  • 简单的应用
  • in another domain where Assembly.GetEntryAssembly() would return null
  • 在另一个域中,Assembly.GetEntryAssembly()将返回null
  • DLL is loaded from Embedded resources as byte array and loaded to AppDomain as Assembly.Load(byteArrayOfEmbeddedDll)
  • DLL从嵌入式资源中加载为字节数组,并作为组合加载到AppDomain。

#23


0  

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

获取应用程序可执行路径的不同方法

#24


-1  

Here is a reliable solution that works with 32bit and 64bit applications.

这是一个可靠的解决方案,适用于32位和64位的应用程序。

Add these references:

添加这些引用:

using System.Diagnostics;

使用System.Diagnostics;

using System.Management;

使用System.Management;

Add this method to your project:

将此方法添加到您的项目中:

public static string GetProcessPath(int processId)
{
    string MethodResult = "";
    try
    {
        string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;

        using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
        {
            using (ManagementObjectCollection moc = mos.Get())
            {
                string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();

                MethodResult = ExecutablePath;

            }

        }

    }
    catch //(Exception ex)
    {
        //ex.HandleException();
    }
    return MethodResult;
}

Now use it like so:

现在像这样使用它:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.

注意,如果您知道进程的id,那么该方法将返回相应的ExecutePath。

Extra, for those interested:

额外的,对这些感兴趣:

Process.GetProcesses() 

...will give you an array of all the currently running processes, and...

…将为您提供当前运行的所有进程的数组,并且…

Process.GetCurrentProcess()

...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*

…会给你目前的流程,以及他们的信息,如Id等,以及限制控制,如杀人等*

#25


-5  

You can create a folder name as Resources within the project using Solution Explorer,then you can paste a file within the Resources.

您可以使用解决方案资源管理器在项目中创建一个文件夹名称作为资源,然后您可以在资源中粘贴一个文件。

private void Form1_Load(object sender, EventArgs e) {
    string appName = Environment.CurrentDirectory;
    int l = appName.Length;
    int h = appName.LastIndexOf("bin");
    string ll = appName.Remove(h);                
    string g = ll + "Resources\\sample.txt";
    System.Diagnostics.Process.Start(g);
}

#1


1019  

System.Reflection.Assembly.GetExecutingAssembly().Location1

.Location1 System.Reflection.Assembly.GetExecutingAssembly()

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

将其与System.IO.Path结合。如果您想要的是目录,那么GetDirectoryName。

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.

根据Mr.Mindor的评论:System.Reflection.Assembly.GetExecutingAssembly()Location返回当前执行程序集所在的位置,该位置可能在不执行时也可能不在程序集所在的位置。对于影子复制程序集,您将在临时目录中获得一条路径。System.Reflection.Assembly.GetExecutingAssembly()。代码库将返回程序集的“永久”路径。

#2


355  

You can use the following code to get the current application directory.

可以使用以下代码获取当前应用程序目录。

AppDomain.CurrentDomain.BaseDirectory

#3


116  

You have two options for finding the directory of the application, which you chose will depend on your purpose.

您有两个选项可以找到应用程序的目录,您选择的目录将取决于您的目的。

// to get the location the assembly is executing from
//(not necessarily where the it normally resides on disk)
// in the case of the using shadow copies, for instance in NUnit tests, 
// this will be in a temp directory.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;

//To get the location the assembly normally resides on disk or the install directory
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

//once you have the path you get the directory with:
var directory = System.IO.Path.GetDirectoryName(path);

#4


72  

Probably a bit late but this is worth a mention:

可能有点晚了,但值得一提:

Environment.GetCommandLineArgs()[0];

Or more correctly to get just the directory path:

或更准确地获取目录路径:

System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

Edit:

编辑:

Quite a few people have pointed out that GetCommandLineArgs is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.

很多人指出GetCommandLineArgs不能保证返回程序名。在命令行上看到的第一个单词是程序名,它只是按惯例命名的。这篇文章确实指出,“尽管使用这种怪癖的Windows程序非常少(我自己也不知道)”。因此,“欺骗”getlineargs是可能的,但我们讨论的是控制台应用程序。控制台应用程序通常又快又脏。这与我的吻哲学相吻合。

#5


36  

For anyone interested in asp.net web apps. Here are my results of 3 different methods

对于任何对asp.net web应用程序感兴趣的人。以下是我用三种不同方法得出的结果

protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}

result

结果

p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging

the app is physically running from "C:\inetpub\SBSPortal_staging", so the first solution is definitely not appropriate for web apps.

这个应用程序在物理上运行于“C:\inetpub\SBSPortal_staging”,所以第一个解决方案肯定不适合web应用程序。

#6


34  

The answer above was 90% of what I needed, but returned a Uri instead of a regular path for me.

上面的答案是我所需的90%,但是返回一个Uri而不是常规路径。

As explained in the MSDN forums post, How to convert URI path to normal filepath?, I used the following:

如MSDN论坛文章中所解释的,如何将URI路径转换为普通的文件路径?,我使用以下资料:

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;

#7


26  

You may be looking to do this:

你可能想这样做:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

#8


18  

you can use this one instead.

你可以用这个。

System.Environment.CurrentDirectory

#9


16  

For Console Applications, you can try this:

对于控制台应用程序,您可以尝试以下操作:

System.IO.Directory.GetCurrentDirectory();

Output (on my local machine):

输出(在本地机器上):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

c:\ \ xxxxxxx \用户文档\ visual studio 2012 \ \ ImageHandler \ GetDir \ bin \调试项目

Or you can try (there's an additional backslash in the end):

或者你也可以试试(最后还有一个反斜杠):

AppDomain.CurrentDomain.BaseDirectory

Output:

输出:

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

c:\ \ xxxxxxx \用户文档\ visual studio 2012 \ ImageHandler \ GetDir \ bin \ \项目调试\

#10


11  

I have used this code and get the solution.

我使用了这段代码并得到了解决方案。

AppDomain.CurrentDomain.BaseDirectory

#11


7  

I use this if the exe is supposed to be called by double clicking it

如果exe应该通过双击来调用,我就使用这个。

var thisPath = System.IO.Directory.GetCurrentDirectory();

#12


7  

I have used

我已经使用

System.AppDomain.CurrentDomain.BaseDirectory

when I want to find a path relative to an applications folder. This works for both ASP.Net and winform applications. It also does not require any reference to System.Web assemblies.

当我想查找与应用程序文件夹相关的路径时。这对ASP都有效。净和winform上应用。它也不需要任何对系统的引用。Web组件。

#13


7  

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

您可以简单地将其添加到项目引用系统。windows中。然后使用System.Windows.Forms.Application。StartupPath像往常一样。

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

因此,不需要更复杂的方法或使用反射。

#14


5  

I mean, why not a p/invoke method?

为什么不使用p/invoke方法呢?

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    public class AppInfo
    {
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
            private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
            private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
            public static string StartupPath
            {
                get
                {
                    StringBuilder stringBuilder = new StringBuilder(260);
                    GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
                    return Path.GetDirectoryName(stringBuilder.ToString());
                }
            }
    }

You would use it just like the Application.StartupPath:

你会像使用程序一样使用它。

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

#15


4  

Assembly.GetEntryAssembly().Location or Assembly.GetExecutingAssembly().Location

Assembly.GetEntryAssembly()。.Location位置或Assembly.GetExecutingAssembly()

Use in combination with System.IO.Path.GetDirectoryName() to get only the directory.

与System.IO.Path.GetDirectoryName()结合使用,只获取目录。

The paths from GetEntryAssembly() and GetExecutingAssembly() can be different, even though for most cases the directory will be the same.

GetEntryAssembly()和GetExecutingAssembly()的路径可以不同,尽管在大多数情况下,目录是相同的。

With GetEntryAssembly() you have to be aware that this can return null if the entry module is unmanaged (ie C++ or VB6 executable). In those cases it is possible to use GetModuleFileName from the Win32 API:

使用GetEntryAssembly(),您必须知道,如果入口模块不受管理(即c++或VB6可执行文件),则可以返回null。在这些情况下,可以使用Win32 API中的GetModuleFileName:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);

#16


4  

AppDomain.CurrentDomain.BaseDirectory

Will resolve the issue to refer the 3rd party reference files with installation packages.

将解决提交第三方参考文件与安装包的问题。

#17


3  

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

如果你正在寻找一种。net核心兼容的方式,使用

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.

这是在。net Framework 4.6和。net Core 1.0(和。net Standard 1.3)中引入的。看到:AppContext。BaseDirectory财产。

According to this page,

根据这个页面,

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

这是AppDomain.CurrentDomain的首选项。BaseDirectory在。net核心

#18


2  

None of these methods work in special cases like using a symbolic link to the exe, they will return the location of the link not the actual exe.

这些方法在特殊情况下都不起作用,比如使用符号链接到exe,它们将返回链接的位置,而不是实际的exe。

So can use QueryFullProcessImageName to get around that:

所以可以使用QueryFullProcessImageName来解决这个问题:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);

    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern IntPtr OpenProcess(
        UInt32 dwDesiredAccess,
        [MarshalAs(UnmanagedType.Bool)]
        Boolean bInheritHandle,
        Int32 dwProcessId
    );
}

public static class utils
{

    private const UInt32 PROCESS_QUERY_INFORMATION = 0x400;
    private const UInt32 PROCESS_VM_READ = 0x010;

    public static string getfolder()
    {
        Int32 pid = Process.GetCurrentProcess().Id;
        int capacity = 2000;
        StringBuilder sb = new StringBuilder(capacity);
        IntPtr proc;

        if ((proc = NativeMethods.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)) == IntPtr.Zero)
            return "";

        NativeMethods.QueryFullProcessImageName(proc, 0, sb, ref capacity);

        string fullPath = sb.ToString(0, capacity);

        return Path.GetDirectoryName(fullPath) + @"\";
    }
}

#19


2  

Try this simple line of code:

试试下面这行简单的代码:

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);

#20


2  

in VB.net

在VB.net

My.Application.Info.DirectoryPath

works for me (Application Type: Class Library). Not sure about C#... Returns the path w/o Filename as string

适合我(应用类型:类库)。不确定关于c#…返回路径w/o文件名作为字符串

#21


0  

I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.

我没有看到任何人将. net核心反射提供的LocalPath转换成可用的系统。IO路径,这是我的版本。

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;

}

This will return the full "C:\xxx\xxx" formatted path to where your code is.

这将返回完整的“C:\xxx\xxx”格式的路径到代码所在的位置。

#22


0  

Following line will give you an application path:

下面的代码将为您提供一个应用程序路径:

var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

Above solution is working properly in following situations:

上述解决方案在以下情况下工作正常:

  • simple app
  • 简单的应用
  • in another domain where Assembly.GetEntryAssembly() would return null
  • 在另一个域中,Assembly.GetEntryAssembly()将返回null
  • DLL is loaded from Embedded resources as byte array and loaded to AppDomain as Assembly.Load(byteArrayOfEmbeddedDll)
  • DLL从嵌入式资源中加载为字节数组,并作为组合加载到AppDomain。

#23


0  

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

获取应用程序可执行路径的不同方法

#24


-1  

Here is a reliable solution that works with 32bit and 64bit applications.

这是一个可靠的解决方案,适用于32位和64位的应用程序。

Add these references:

添加这些引用:

using System.Diagnostics;

使用System.Diagnostics;

using System.Management;

使用System.Management;

Add this method to your project:

将此方法添加到您的项目中:

public static string GetProcessPath(int processId)
{
    string MethodResult = "";
    try
    {
        string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;

        using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
        {
            using (ManagementObjectCollection moc = mos.Get())
            {
                string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();

                MethodResult = ExecutablePath;

            }

        }

    }
    catch //(Exception ex)
    {
        //ex.HandleException();
    }
    return MethodResult;
}

Now use it like so:

现在像这样使用它:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.

注意,如果您知道进程的id,那么该方法将返回相应的ExecutePath。

Extra, for those interested:

额外的,对这些感兴趣:

Process.GetProcesses() 

...will give you an array of all the currently running processes, and...

…将为您提供当前运行的所有进程的数组,并且…

Process.GetCurrentProcess()

...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*

…会给你目前的流程,以及他们的信息,如Id等,以及限制控制,如杀人等*

#25


-5  

You can create a folder name as Resources within the project using Solution Explorer,then you can paste a file within the Resources.

您可以使用解决方案资源管理器在项目中创建一个文件夹名称作为资源,然后您可以在资源中粘贴一个文件。

private void Form1_Load(object sender, EventArgs e) {
    string appName = Environment.CurrentDirectory;
    int l = appName.Length;
    int h = appName.LastIndexOf("bin");
    string ll = appName.Remove(h);                
    string g = ll + "Resources\\sample.txt";
    System.Diagnostics.Process.Start(g);
}