Reputation: 67
Here AppContext.BaseDirectory always returning C:\Windows\System32 but we are expecting D:\MyCustomService - where we have the actual files.
Please find my following code. Can you please suggest where it's going wrong and also I have tried all other options like CurrentDirectory, System.Reflection.Assembly.GetEntryAssembly().Location, Process.GetCurrentProcess().MainModule.FileName; etc
We have installed the server by using following command
sc create "myServiceName" binPath="D:\MyCustomService\myServiceName.exe"
public class Program
{
public static void Main(string[] args)
{
const string loggerTemplate = @"{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u4}]<{ThreadId}> [{SourceContext:l}] {Message:lj}{NewLine}{Exception}";
var baseDir = AppContext.BaseDirectory;
Console.WriteLine(baseDir);
var logfile = Path.Combine(baseDir, "App_Data", "logs", "log.txt");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.With(new ThreadIdEnricher())
.Enrich.FromLogContext()
.WriteTo.Console(LogEventLevel.Information, loggerTemplate, theme: AnsiConsoleTheme.Literate)
.WriteTo.File(logfile, LogEventLevel.Information, loggerTemplate, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 90)
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.UseWindowsService();
}
Upvotes: 4
Views: 3891
Reputation: 111
use IHostEnviroment, in Development or Staging you can use Directory.GetCurrentDirectory(), but in production you have to use _environment.ContentRootPath because default path for windows services is "C:\Windows\system32"
Upvotes: 1
Reputation: 1545
Apparently you can not because a Windows service runs in the folder you mention, read Microsoft documentation:
Don't attempt to use GetCurrentDirectory to obtain a resource path because a Windows Service app returns the C:\WINDOWS\system32 folder as its current directory.
Upvotes: 1