In the Windows system to do network development, most of the time is the use of Windows Service mode, but in the scheduling phase, we are more using the console mode. At the time of development, we judge the program's main entrance. Originally started using the Environment.userinteractive property, in the system does not system service interaction mode, the program is normal, but tried to have Win7, the system allows interactive mode, the results when the service started, jump to the console mode, the service does not start up. You can only take parameters in the invocation mode of the service, and then determine whether the service is in the parameters of Main. This can solve the problem in the general situation.
Later, there are several projects, using the open-source socket framework, the framework itself is configured to start the service, so that there is no user's main method, the start of the method with parameters, if you want to determine the startup mode and add a separate configuration, not very good practice, Through the program and the global identity is able to solve the process itself start with the framework of the judgment, but the service if it is through its own main start, but only by adding parameters to the method, the whole realization feeling is a bit awkward.
In several service program development, encountered a write file path problem, that is, fetch path is always wrong, through analysis, Windows service startup environment default path is from the System32 directory, may be the Windows Service Host program is from here, There is a way to figure out how to determine the startup mode. This is primarily done by the host program, which is the directory in which the Assembly resides. Specific as follows:
string curpath = System.Environment.CurrentDirectory;
String basepath = Path.getdirectoryname (System.AppDomain.CurrentDomain.BaseDirectory);
BOOL Isrunwinservice = (Curpath! = BasePath);
If the two paths are different, I think it's starting the Windows service. We just have to judge at the beginning of the program, so that the environment.currentdirectory path is the host program, in general, developers rarely change environment.currentdirectory. So we do the EXE program to support user start, service start, or framework automatic service management mode.
C # Judging If a program is started by a Windows service or by a user