Windows Service & Windows Application?

T

Tbone

Is there any way to have my C# executable file be runnable as a Windows
Application AND runnable as a Windows Service? I know I can create a
separate project for the Windows Service, but I am wondering if there is a
way to do this with a single executable?
 
P

Peter Bromberg [C# MVP]

This is how I do it for running as plain old EXE while debugging. What you
need would be similar:

private static void Main(string[] args)
{
string opt = null;
// check for arguments
if (args.Length > 0)
{
opt = args[0];
if (opt != null && opt.ToLower() == "/install")
{
TransactedInstaller ti = new TransactedInstaller();
ProjectInstaller pi = new ProjectInstaller();
ti.Installers.Add(pi);
String path = String.Format("/assemblypath={0}",
Assembly.GetExecutingAssembly().Location);
String[] cmdline = {path};
InstallContext ctx = new InstallContext("", cmdline);
ti.Context = ctx;
ti.Install(new Hashtable());
}
else if (opt != null && opt.ToLower() == "/uninstall")
{
TransactedInstaller ti = new TransactedInstaller();
ProjectInstaller mi = new ProjectInstaller();
ti.Installers.Add(mi);
String path = String.Format("/assemblypath={0}",
Assembly.GetExecutingAssembly().Location);
String[] cmdline = {path};
InstallContext ctx = new InstallContext("", cmdline);
ti.Context = ctx;
ti.Uninstall(null);

}
}
if (opt == null) // e.g. ,nothing on the command line
{
#if ( ! DEBUG )
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] {new Service1()};
ServiceBase.Run(ServicesToRun);


#else
// debug code: allows the process to run as a non-service
// will kick off the service start point, but never kill it
// shut down the debugger to exit
Service1 service = new Service1();
service.OnStart(null);


Thread.Sleep(Timeout.Infinite);
#endif

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top