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:54

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
  • DLL is loaded from Embedded resources as byte array and loaded to AppDomain as Assembly.Load(byteArrayOfEmbeddedDll)
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 02:54

You can use following code, you will get application full path:

 class Program
{
    static void Main(string[] args)
    {
        string AppPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        WriteLine($"ApplicationPath ---{AppPath}");
        //OutPut// //ApplicationPath---C:\Users\TestUser\source\repos\ThreadStack\ThreadStack\bin\Debug\ThreadStack.exe
        ReadLine();
    }
}  
查看更多
美炸的是我
4楼-- · 2018-12-31 02:55

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);
}
查看更多
情到深处是孤独
5楼-- · 2018-12-31 02:57
AppDomain.CurrentDomain.BaseDirectory

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

查看更多
其实,你不懂
6楼-- · 2018-12-31 02:59

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

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

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;
查看更多
余生无你
7楼-- · 2018-12-31 02:59

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.

So can use QueryFullProcessImageName to get around that:

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) + @"\";
    }
}
查看更多
登录 后发表回答