I'm developing a windows service using Topshelf library... I want to start cmd and map a folder from my network and run an console application from it.
This is my whole class:
class ClientService
{
private Scheduler ServiceScheduler { get; set; }
private Process MyApp{ get; set; }
private Config ConfigFile { get; set; }
public void Start()
{
ServiceScheduler = new Scheduler(6000) { Enabled = true };
ServiceScheduler.Elapsed += Scheduler_Elapsed;
ConfigFile =Config.get();
ConfigMyApp();
}
private void ConfigMyApp() => ConfigMyApp= new Process
{
StartInfo =
{
CreateNoWindow = false,
ErrorDialog = false,
UseShellExecute = false,
RedirectStandardInput = true,
FileName = "CMD.exe",
}
};
private void Scheduler_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (Network.CurrentHourMin == ConfigFile.StartTime)
{
MyApp.Start();
using (var sw = MyApp.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
//Map My Folder Network
sw.WriteLine("pushd \\\\MyNetwork\\General\\");
//Run MyApp with Args
sw.WriteLine(MyApp -run -args -others);
}
}
}
else if (Network.CurrentHourMin == ConfigFile.EndTime)
{
//////////
How To stop running MyApp.exe
//////////
}
}
public void Stop()
{
}
}
The problem is I can't close MyApp.exe that previously ran from cmd.exe and doing MyApp.Close won't stop running the application and doesn't any affect at all.
Even Calling Stop method from Topshelf service (or stopping the service) doesn't stop running MyApp What is the best practice for Exit or kill an Console application in this scenario?
Don't create processes unless you have to. Here's some code to map a network drive:
public void mapDrive(string driveLetter, string networkPath, bool isPersistent)
{
private WshNetwork _networkShell = new WshNetwork();
object persistent = isPersistent;
_networkShell.MapNetworkDrive(driveLetter, networkPath, ref persistent) ;
}
You'll need a reference to Windows Script Host Object Model.
You'll have better control over the exception handling if you keep it in process.