473,789 Members | 2,441 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Window Service & C#

Hi,

I have a window service program created in c#. The window service program is
installed and running. In the mean time, I have another c# application, I
would like to know if there is a way to find out in this c# application where
(the complete path)the window service program is running from. Can someone
provide the sample code?
Thanks.

Potsang
Feb 16 '07 #1
9 2488
I use string
startpath=Path. GetDirectoryNam e(Environment.C ommandLine.Repl ace('"',' '));

"Potsang" <po*****@newsgr oups.nospamha scritto nel messaggio
news:14******** *************** ***********@mic rosoft.com...
Hi,

I have a window service program created in c#. The window service program
is
installed and running. In the mean time, I have another c# application, I
would like to know if there is a way to find out in this c# application
where
(the complete path)the window service program is running from. Can someone
provide the sample code?
Thanks.

Potsang

Feb 16 '07 #2
Here is a sample code..

Process[] processList = Process.GetProc esses();
string processPath = string.Empty;
//Get the list of current processes running on your machine

foreach (Process proc in processList)
{
//Compare the processName with your process name
if (proc.ProcessNa me == "YourProcessNam e")
{
//The MainModule.File Name returns the complete path of
//the exe that it is running from
processPath = proc.MainModule .FileName;
}

}
System.Console. WriteLine(proce ssPath);

--
Thinathayalan Ganesan
http://CyberSannyasi.blogspot.com
"Potsang" wrote:
Hi,

I have a window service program created in c#. The window service program is
installed and running. In the mean time, I have another c# application, I
would like to know if there is a way to find out in this c# application where
(the complete path)the window service program is running from. Can someone
provide the sample code?
Thanks.

Potsang
Feb 16 '07 #3
Here is the more refined code than man previous one...

using System.Diagnost ics
Process p = Process.GetProc essesByName("Yo urProcessName") ;
string processPath = p.MainModule.Fi leName;

--
Thinathayalan Ganesan
http://CyberSannyasi.blogspot.com
"Thinathaya lan Ganesan" wrote:
Here is a sample code..

Process[] processList = Process.GetProc esses();
string processPath = string.Empty;
//Get the list of current processes running on your machine

foreach (Process proc in processList)
{
//Compare the processName with your process name
if (proc.ProcessNa me == "YourProcessNam e")
{
//The MainModule.File Name returns the complete path of
//the exe that it is running from
processPath = proc.MainModule .FileName;
}

}
System.Console. WriteLine(proce ssPath);

--
Thinathayalan Ganesan
http://CyberSannyasi.blogspot.com
"Potsang" wrote:
Hi,

I have a window service program created in c#. The window service program is
installed and running. In the mean time, I have another c# application, I
would like to know if there is a way to find out in this c# application where
(the complete path)the window service program is running from. Can someone
provide the sample code?
Thanks.

Potsang
Feb 16 '07 #4
Hi Potsang,

Thinathayalan's reply has shown how to enumerate all the running processes
to find your "Windows Service" and get its full path. I think it should
meet your need. I want to provide some more information to you.

If you want to retrieve the full path to the "Windows Service" when it is
not running, you can not use System.Diagnost ics.Process class solution. In
this requirement, you have to use QueryServiceCon fig Win32 API to obtain
the installed service binary full path. However, .Net did not expose this
QueryServiceCon fig API from class library, so you have to p/invoke to call
it. You may use the logic below:
1. Use ServiceControll er.GetServices method to retrieve all the services
installed on your system.
2. Enumerate through this services list and compare
ServiceControll er.ServiceName property to find your service
ServiceControll er reference.
3. Then p/invoke QueryServiceCon fig win32 API by passing
ServiceControll erServiceHandle .handle to it. The retrieved
QUERY_SERVICE_C ONFIG structure has a field of lpBinaryPathNam e, which
contains the full binary path of the service.

My original reply below contains some more information:
http://groups.google.com/group/micro...es.vb/msg/6452
aa87e538615f?hl =zh-CN&

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 19 '07 #5
"Potsang" <po*****@newsgr oups.nospamwrot e in message
news:14******** *************** ***********@mic rosoft.com...
Hi,

I have a window service program created in c#. The window service program is
installed and running. In the mean time, I have another c# application, I
would like to know if there is a way to find out in this c# application where
(the complete path)the window service program is running from. Can someone
provide the sample code?
Thanks.

Potsang

Nothing easier than using System.Manageme nt for this.
string objPath = "Win32_Service. Name='spooler'" ;
string servicePath = null;
using(Managemen tObject service = new ManagementObjec t( new ManagementPath( objPath)))
{
servicePath = (string)service .Properties["PathName"].Value;
}
....

Willy.

Feb 19 '07 #6
""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:ld******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Potsang,

Thinathayalan's reply has shown how to enumerate all the running processes
to find your "Windows Service" and get its full path. I think it should
meet your need. I want to provide some more information to you.

If you want to retrieve the full path to the "Windows Service" when it is
not running, you can not use System.Diagnost ics.Process class solution. In
this requirement, you have to use QueryServiceCon fig Win32 API to obtain
the installed service binary full path. However, .Net did not expose this
QueryServiceCon fig API from class library, so you have to p/invoke to call
it. You may use the logic below:
1. Use ServiceControll er.GetServices method to retrieve all the services
installed on your system.
2. Enumerate through this services list and compare
ServiceControll er.ServiceName property to find your service
ServiceControll er reference.
3. Then p/invoke QueryServiceCon fig win32 API by passing
ServiceControll erServiceHandle .handle to it. The retrieved
QUERY_SERVICE_C ONFIG structure has a field of lpBinaryPathNam e, which
contains the full binary path of the service.

My original reply below contains some more information:
http://groups.google.com/group/micro...es.vb/msg/6452
aa87e538615f?hl =zh-CN&

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

No need to go down the PInvoke route, System.Manageme nt contains all classes needed to
perform management tasks like this, isn't the purpose of the FCL to eliminate the need to
call into Win32 just like we do from unmanaged code?

Willy.

Feb 19 '07 #7
Hi Willy ,

Oh, thank you for sharing the WMI solution! Yes, Win32_Service should be a
correct solution and by using System.Manageme nt we can use WMI in .Net
without p/invoke unmanaged code.

I am always a Win32 API guy, so I seldom thought solution from WMI
perspective :-)

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 20 '07 #8
""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:lK******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Willy ,

Oh, thank you for sharing the WMI solution! Yes, Win32_Service should be a
correct solution and by using System.Manageme nt we can use WMI in .Net
without p/invoke unmanaged code.

I am always a Win32 API guy, so I seldom thought solution from WMI
perspective :-)

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jeffrey,

I'm a Win32 guy too, however, System.Manageme nt/WMI virtualizes Win32 which guarantees you
to do the right thing. Another great advantage is that you don't need to run in an
administrator account to perform administrative tasks, something you will appreciate when
moving to Vista.

Willy.

Feb 20 '07 #9
The easiest way to get the path to a service.

/// <summary>
/// Fully-qualified path to the service binary file that
implements the
/// service
/// </summary>
/// <param name="serviceNa me">string</param>
/// <returns>string </returns>
public static string GetPathName(str ing serviceName)
{
string buffer;
ConnectionOptio ns _co = null;
ManagementScope _ms = null;
ManagementObjec t _mo = null;
try
{
_co = new ConnectionOptio ns();
_co.Impersonati on = ImpersonationLe vel.Impersonate ;
_ms = new ManagementScope (@"root\CIMV2 ", _co);
_ms.Connect();

_mo = new
ManagementObjec t(String.Format ("Win32_Service .Name='{0}'",
serviceName));

buffer =
Convert.ToStrin g(_mo.GetProper tyValue("PathNa me"));
}
finally
{
_mo.Dispose();
_mo = null;

if (_ms != null)
{
_ms = null;
if (_co != null)
{
_co = null;
}
}
}
return buffer;
}
*** Sent via Developersdex http://www.developersdex.com ***
Mar 5 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1309
by: MichaelC | last post by:
Hi, I'v created NT service using Windows service project template. Now , I want to recieve WM_USERCHANGE and WM_DEICECHANGE messages after the service started. How can i do this? Thanks.
6
9083
by: Siegfried Heintze | last post by:
I have the following C# code in my web service: public static extern double add_(double X, double Y ); public double add (double X, double Y){ return add_(X, Y); }
7
8639
by: =?Utf-8?B?Vmlua2k=?= | last post by:
public void sendKeysTest() { Process myProcess = Process.Start(@"C:\winnt\system32\cmd.exe"); SetForegroundWindow(myProcess.Handle); if (myProcess.Responding) SendKeys.SendWait("{ENTER}"); else
1
2877
by: mdhaman | last post by:
hi, I have a windows service written in VB.Net and framework 2.0. It is a multithread service and it is using threadpool to manage threads. Recently I have started getting NullReferenceException and after that windows service crashes. System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"
0
1913
by: henkya | last post by:
Language Used: C# Project Typed: Setup Project (for .NET Window Service) Hi Bump into this issue and seriously have a hunch that this is a bug in the .NET setup project. These are the scenario: - I have an existing Window-Service application written in C#, and was build following the general deploying Window-Service guideline (the Win-Service project has a Installer class that have ServiceProcessInstaller & ServiceInstaller that...
2
3269
by: wreed06 | last post by:
Hello, I have 2 problems. In my webpage, I have a dropdown list with a button that takes the user to a popup window specific to the option. I am using Firefox 2.0.0.13. I have successfully validated my HTML and CSS code. 1. When I clear cache and refresh my webpage, it takes 3 tries before the popup window displays - I click on the button once, a white window the size of my webpage displays. I close it and click on the button again (for...
2
1736
by: gray d newbie | last post by:
Greetings All, This is my first time creating a Window Service and I am having this error message when I try to start my window service (currently known as Service1). Below is my code for Window Service and also the line which I suspected is the caused of the problem. Protected Overrides Sub OnStart(ByVal args() As String) Dim i As Integer i = Shell("\\202.186.196.128\c$\Inetpub\wwwroot\WebAdmin\Rewards\print.exe",...
1
3175
by: vinpkl | last post by:
hi all i have two dynamic drop downs of dealer id and category id which work properly with window.location var dealerid; function getList(xyz) { window.location='manage_products.php?category_id=' + xyz; }
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10404
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10195
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10136
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5415
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.