Jak mogę pobrać ścieżkę aplikacji a.NET aplikacja konsolowa?

Jak znaleźć ścieżkę aplikacji w aplikacji konsolowej?

W Windows Forms mogę użyć Application.StartupPath, aby znaleźć bieżącą ścieżkę, ale wydaje się, że nie jest ona dostępna w aplikacji konsolowej.

Author: Peter Mortensen, 2009-05-07

27 answers

System.Reflection.Assembly.GetExecutingAssembly().Location1

Połącz to z System.IO.Path.GetDirectoryName jeśli chcesz tylko katalog.

1zgodnie z komentarzem Pana Mindora:
System.Reflection.Assembly.GetExecutingAssembly().Location zwraca miejsce, w którym aktualnie znajduje się wykonujący zespół, które może lub nie musi znajdować się tam, gdzie znajduje się zespół, gdy nie jest wykonywany. W przypadku kopiowania w cieniu złożeń, otrzymasz ścieżkę w katalogu tymczasowym. System.Reflection.Assembly.GetExecutingAssembly().CodeBase zwróci "stałą" ścieżkę montaż.

 1230
Author: Sam Axe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-14 08:48:54

Możesz użyć poniższego kodu, aby uzyskać bieżący katalog aplikacji.

AppDomain.CurrentDomain.BaseDirectory
 425
Author: Richard Ev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-22 12:39:53

Masz dwie opcje znalezienia katalogu aplikacji, który wybierzesz będzie zależał od Twojego celu.

// 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);
 186
Author: Mr.Mindor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-09 19:20:04

Pewnie trochę za późno, ale warto o tym wspomnieć:

Environment.GetCommandLineArgs()[0];

Lub bardziej poprawnie, aby uzyskać tylko ścieżkę katalogu:

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

Edit:

Sporo osób zauważyło, że GetCommandLineArgs nie ma gwarancji powrotu nazwy programu. Zobacz pierwszym słowem w wierszu poleceń jest nazwa programu tylko według konwencji . Artykuł stwierdza, że " chociaż wyjątkowo niewiele programów Windows używa tego dziwactwa (sam nie jestem tego świadomy)". Tak więc możliwe jest 'spoof' GetCommandLineArgs, ale mówimy o aplikacji konsolowej. Aplikacje konsolowe są zwykle szybkie i brudne. Więc to pasuje do mojej filozofii pocałunku.

 86
Author: Steve Mc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-27 09:17:55

Dla wszystkich zainteresowanych asp.net aplikacje internetowe. Oto moje wyniki 3 różnych metod

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);
}

Wynik

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

Aplikacja działa fizycznie z "C:\inetpub\SBSPortal_staging", więc pierwsze rozwiązanie zdecydowanie nie jest odpowiednie dla aplikacji internetowych.

 47
Author: rocketsarefast,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-06 19:42:16

Powyższa odpowiedź stanowiła 90% tego, czego potrzebowałem, ale zwróciła mi Uri zamiast zwykłej ścieżki.

Jak wyjaśniono w poście na forum MSDN, Jak przekonwertować ścieżkę URI na normalną ścieżkę pliku?, użyłem następującego:

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;
 45
Author: fizzled,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-13 20:20:44

Możesz chcieć to zrobić:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
 30
Author: ist_lion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-20 15:41:04

Jeśli szukasz sposobu zgodnego z. NET Core, użyj

System.AppContext.BaseDirectory
[1]}zostało to wprowadzone w.NET Framework 4.6 i. Net Core 1.0 (oraz. Net Standard 1.3). Zobacz: AppContext.Właściwość BaseDirectory .

Według tej strony ,

Jest to preferowany zamiennik dla AppDomain.CurrentDomain.BaseDirectory w. Net Core

 26
Author: Dejan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-02 02:14:02

Możesz użyć tego.

System.Environment.CurrentDirectory
 24
Author: ButtShock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-16 13:34:02

Dla aplikacji konsolowych, możesz spróbować tego:

System.IO.Directory.GetCurrentDirectory();

Wyjście (na mojej lokalnej maszynie):

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

Lub możesz spróbować (na końcu jest dodatkowy ukośnik wsteczny):

AppDomain.CurrentDomain.BaseDirectory

Wyjście:

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

 19
Author: F.Alves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-18 22:03:32

Użyłem tego kodu i uzyskałem rozwiązanie.

AppDomain.CurrentDomain.BaseDirectory
 15
Author: Trimantra Software Solution,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 08:17:40

Następujący wiersz wyświetli ścieżkę aplikacji:

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

Powyższe rozwiązanie działa poprawnie w następujących sytuacjach:

  • prosta aplikacja
  • w innej domenie, gdzie montaż.GetEntryAssembly () zwróci null
  • DLL jest ładowany z osadzonych zasobów jako tablica bajtów i ładowany do AppDomain jako Assembly.Load (byteArrayOfEmbeddedDll)
  • z wiązkami Mono mkbundle (Inne metody nie działają)
 12
Author: user2126375,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-06 10:57:38

Możesz po prostu dodać do swojego projektu referencje System.Windows.Forms, a następnie użyć System.Windows.Forms.Application.StartupPath Jak zwykle .

Więc, nie potrzeba bardziej skomplikowanych metod lub korzystania z odbicia.

 9
Author: fruggiero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-09 12:27:58

Używam tego, jeśli exe ma być wywołane przez podwójne kliknięcie

var thisPath = System.IO.Directory.GetCurrentDirectory();
 7
Author: developer747,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-10 22:07:58

Użyłem

System.AppDomain.CurrentDomain.BaseDirectory

Gdy chcę znaleźć ścieżkę względem folderu aplikacji. Działa to zarówno dla ASP.Net i aplikacji winform. Nie wymaga również odniesienia do systemu.Web assemblies.

 7
Author: user2346593,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-07 16:57:01

Dlaczego nie metoda 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());
                }
            }
    }

Użyłbyś go tak, jak aplikacja.StartupPath:

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
 6
Author: user3596865,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 20:56:42

Assembly.GetEntryAssembly().Location lub Assembly.GetExecutingAssembly().Location

Użyj w połączeniu z System.IO.Path.GetDirectoryName(), aby uzyskać tylko katalog.

Ścieżki z GetEntryAssembly() i GetExecutingAssembly() mogą być różne, chociaż w większości przypadków katalog będzie taki sam.

Z GetEntryAssembly() musisz być świadomy, że może to zwrócić {[7] } jeśli moduł wejściowy jest niezarządzany(np. C++ lub VB6). W takich przypadkach możliwe jest użycie GetModuleFileName z API Win32:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
 5
Author: Herman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 15:40:02

W VB.net

My.Application.Info.DirectoryPath

Działa dla mnie (Typ aplikacji: Biblioteka klas). Nie jestem pewien co do C#... Zwraca ścieżkę bez nazwy pliku jako ciąg znaków

 5
Author: dba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-16 02:45:23
AppDomain.CurrentDomain.BaseDirectory

Rozwiąże problem z odesłaniem plików referencyjnych innych firm za pomocą pakietów instalacyjnych.

 4
Author: Nirav Mehta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-14 06:43:49

Spróbuj tego prostego wiersza kodu:

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);
 3
Author: daniele3004,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-20 09:42:03

Nie widziałem, żeby ktoś przekonwertował ścieżkę lokalną dostarczoną przez. Net Core reflection na użyteczną System.IO / align = "left" /

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

   return new FileInfo(exePath).DirectoryName;
       
}

Zwróci pełną C:\\xxx\\xxx sformatowaną ścieżkę do miejsca, w którym znajduje się Twój kod.

 2
Author: mark gamache,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-10 14:06:02

Żadna z tych metod nie działa w szczególnych przypadkach, takich jak użycie dowiązania symbolicznego do exe, zwrócą lokalizację dowiązania, a nie rzeczywisty exe.

Więc można użyć QueryFullProcessImageName aby obejść to:

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) + @"\";
    }
}
 1
Author: colin lamarre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-05 08:54:41

Innym rozwiązaniem jest użycie ścieżek względnych wskazujących na bieżącą ścieżkę:

Path.GetFullPath(".")
 1
Author: blenderfreaky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-22 21:34:03

Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Jest jedynym, który pracował dla mnie w każdym przypadku próbowałem.

 0
Author: Sinned Lolwut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-10 14:04:35

Oto niezawodne rozwiązanie, które współpracuje z aplikacjami 32bit i 64bit.

Dodaj te referencje:

Korzystanie Z Systemu.Diagnostyka;

Korzystanie Z Systemu.Zarządzanie;

Dodaj tę metodę do swojego projektu:

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;
}

Teraz używaj go tak:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

Zauważ, że jeśli znasz id procesu, wtedy ta metoda zwróci odpowiednią ścieżkę ExecutePath.

Extra, dla zainteresowanych:

Process.GetProcesses() 

...da masz tablicę wszystkich aktualnie uruchomionych procesów, oraz...

Process.GetCurrentProcess()

...poda ci bieżący proces, wraz z ich informacjami np. Id, itp. a także ograniczoną kontrolę np. Kill, itp.*

 -1
Author: WonderWorker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Istnieje wiele sposobów na uzyskanie ścieżki wykonywalnej, która z nich powinna być użyta zależy od naszych potrzeb oto link, który omawia różne metody.

Różne sposoby uzyskania ścieżki wykonywalnej aplikacji

 -1
Author: Nasir Mahmood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 07:26:38

Możesz utworzyć nazwę folderu jako zasoby w projekcie za pomocą Eksploratora rozwiązań,a następnie wkleić plik w zasoby.

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
Author: Devarajan.T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-28 11:59:13