简体   繁体   中英

How to get the path of the directory where the .exe file for a .Net Core console application is located?

I want to create a .Net Core console app that gets run by the Windows Task Scheduler. In this console app I want to find the path of the directory where the app's .exe file is located.

I publish the app to create the .exe file by running this line of code in a command prompt: dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true

I believe that this might have something to do with the strange behavior outlined below.

The problem I encounter is that when I run the .exe file the path it gets is not the path to the folder where it is located.

To demonstrate this I have written this console application:

//program.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace PathTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Write(Directory.GetCurrentDirectory());

            Write(Assembly.GetExecutingAssembly().Location);

            Write(Assembly.GetExecutingAssembly().CodeBase);

            Write(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            Write(AppDomain.CurrentDomain.BaseDirectory);

            Write(Environment.GetCommandLineArgs()[0]);

            Write(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));

            Write(Process.GetCurrentProcess().MainModule.FileName);

            Write(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            Console.ReadKey();
        }

        readonly static Action<string> Write = (str) =>
        {
            Console.WriteLine(str);
            Console.WriteLine("");
        };
    }
}

When I debug this program I get this output: debug image

When I run the .exe file I get this output: manual run

When I use Windows Task Scheduler to run the .exe file I get this output: task scheduler image

What I would like to know is: What code should I use to get the path to the directory where the .exe file is located?

Why is the path to a temp folder is being returned?

I have found the answer thanks to this issue: https://github.com/dotnet/runtime/issues/13051

You have to use: Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM