I have a simple console application in C# that create a text file as log when it starts and open the notepad application.
If I run the application manually, it creates de the log file and opens the notepad. However if I create a scheduled task that run the application, the log file is not created but the notepad is opened.
This is when I right click and run the scheduled task to test if it works as expected.
I have realized that the notepad is opened if I configure the scheduled task to start when user log on, but if I configure when system starts, no matter if the user log on or not, then the notepd pad is not opened.
What I would like it is create a scheduled task that run my application and do all the work, create the log file and also open the notepad.
My user is a normal user that is added to the group to start session as log on batch.
This is the code of my console application in NET 7:
try
{
File.WriteAllTextAsync("log.txt", $"{DateTime.Now}: Se ha iniciado la aplicación");
ProcessStartInfo start = new ProcessStartInfo();
//start.Arguments = miStrParametros;
start.FileName = "notepad.exe";
//Se oculta la ventana
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
Process.Start(start);
}
catch (Exception ex)
{
File.AppendAllTextAsync("log.txt", $"{DateTime.Now}: {ex.Message}");
}
Thanks so much.
CodePudding user response:
File.WriteAllTextAsync and File.AppendAllTextAsync write to the file asynchronously, which means that the application continues execution without waiting for the write operation to complete.
This means that the log file may not have been created by the time the application tries to open it.
You can write synchronously to ensure that the log file is created before the app tries opening it.
try
{
File.WriteAllText("log.txt", $"{DateTime.Now}: Se ha iniciado la aplicación");
ProcessStartInfo start = new ProcessStartInfo();
//start.Arguments = miStrParametros;
start.FileName = "notepad.exe";
//Se oculta la ventana
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
Process.Start(start);
}
catch (Exception ex)
{
File.AppendAllText("log.txt", $"{DateTime.Now}: {ex.Message}");
}
I hope this helps.