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?
Sometimes you may want to get the current executable file path of your C# program. The working folder is needed to access settings, database, images, or resource files residing in the same directory as the currently running C# executable file of your program. //C:\Program Files\MyApplication\Settings.
The Application Base (Root) path is available in the ContentRootPath property of the interfaces IHostingEnvironment (. Net Core 2.0) and IWebHostEnvironment (. Net Core 3.0) in ASP.Net Core. The IHostingEnvironment is an interface for .
StartupPath property returns the path for the executable file that started the application, not the path where the application executable is stored. ExecutablePath property returns the path for the executable file that started the application, including the executable name.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With