473,545 Members | 2,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how do you convert a console application to a windows service in C#

2 New Member
How do you convert a console application to a windows service.Any recommendations ? The following code is below

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6.  
  7. using System.Management;
  8. using System.IO;
  9. using System.Text.RegularExpressions;
  10.  
  11. public struct ParamHost 
  12.         {
  13.             public string MAC, hostname,IP;
  14.  
  15.             public ParamHost(string MAC, string hostname, string IP) 
  16.               {
  17.                 this.MAC = MAC;
  18.                 this.hostname = hostname;
  19.  
  20.                 this.IP = IP;
  21.               }
  22.         }
  23.  
  24.  
  25. namespace NetworkCardConfig
  26. {
  27.     class Program
  28.     {
  29.  
  30.  
  31.  
  32.         static void Main(string[] args)
  33.         {
  34.             // Open file MAC.TXT
  35.             // read from file or write to file
  36.             System.IO.FileStream myStream = new FileStream("C:\\MAC.txt", FileMode.Open);
  37.  
  38.             System.IO.StreamReader myStreamReader = new StreamReader(myStream);
  39.  
  40.             string fileContent = myStreamReader.ReadToEnd();
  41.  
  42.             myStreamReader.Close();
  43.  
  44.             string[] Lines = fileContent.Split('\n');
  45.  
  46.             String[] Field;
  47.  
  48.             ParamHost[] PH;
  49.  
  50.  
  51.             PH = new ParamHost[Lines.Length]; // to do 
  52.  
  53.             int PH_Number = 0;
  54.  
  55.  
  56.             foreach (string Line in Lines)
  57.             {
  58.  
  59.                 if (Line != "" && Line != "\r")
  60.                 {
  61.                     Console.WriteLine("line :" + Line);
  62.  
  63.                     Field = Line.Split(';');
  64.  
  65.                     Console.WriteLine("MAC {0}; hostname{1}; IP: {2}", Field[0], Field[1], Field[2]);
  66.  
  67.                     PH[PH_Number].MAC = Field[0];
  68.                     PH[PH_Number].hostname = Field[1];
  69.                     PH[PH_Number].IP = Field[2];
  70.  
  71. /*
  72.                     for (int i = 0; i < Field.Length; i++)
  73.                     {
  74.                     Console.WriteLine(Field[i]);
  75.                     }*/
  76.                     PH_Number++;
  77.  
  78.  
  79.                     //foreach (String i in Field)
  80.                     //{
  81.  
  82.                       //  Console.WriteLine(Field[i]);
  83.  
  84.  
  85.                     //}
  86.                     //PH_Number++;
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.                 }
  95.  
  96.                 // Console.WriteLine("{0}", fileContent);
  97.  
  98.                 myStreamReader.Close();
  99.  
  100.                 //Console.WriteLine(PH[0].MAC);
  101.  
  102.                 ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
  103.  
  104.  
  105.                 ManagementObjectCollection objMOC = objMC.GetInstances();
  106.  
  107.  
  108.                 string gw;
  109.                 string myIpString;
  110.                 char[] delim;
  111.                 string[] myIpArray;
  112.                 string myGateWayString;
  113.  
  114.  
  115.  
  116.                 foreach (ManagementObject objMO in objMOC)
  117.                 {
  118.  
  119.                     if (!(bool)objMO["ipEnabled"])
  120.                         continue;
  121.                     //Console.WriteLine(objMO["Caption"] + "," + objMO["ServiceName"] + "," + objMO["MACAddress"]);
  122.  
  123.                     string MAC_card = objMO["MACAddress"].ToString();
  124.  
  125.                     for (int index = 0; index < PH_Number; index++)
  126.                     {
  127.                         string MAC_File = PH[index].MAC.ToString();
  128.  
  129.                         //Console.WriteLine("jkjkjk :" + MAC_card + MAC_File);
  130.  
  131.                         if (MAC_card.Equals(MAC_File))
  132.                         {
  133.                             Console.WriteLine("good card to configure ! ! " + MAC_File);
  134.                             Console.WriteLine("hostname " + PH[index].hostname);
  135.                             Console.WriteLine("IP " + PH[index].IP);
  136.                             // Set nic parameters
  137.                             // to do
  138.  
  139.                             //string gw = PH[index].IP;
  140.  
  141.  
  142.                             gw = PH[index].IP;
  143.  
  144.                             //PH[index].IP = x.y.z.w -> gw= x.y.z.1
  145.  
  146.                             // to do   gw = .1
  147.  
  148.  
  149.  
  150.                             //assuming myLocalIP is the IPAddress object you are using from the IPAddress array you will have been playing with before...
  151.                             myIpString = gw.ToString(); //to return nice "255.255.255.255" notation to work with
  152.                             delim = new char[1]; //set the delimiter you want to split your IP string by - so '.'
  153.                             delim[0] = '.'; //set the delimiter you want to split your IP string by - so '.'
  154.                             myIpArray = myIpString.Split(delim); //actually split the IP up
  155.                             myIpArray[3] = "1";
  156.                             myGateWayString = myIpArray[0] + "." + myIpArray[1] + "." + myIpArray[2] + "." + myIpArray[3]; //to reconstruct your gateway string
  157.                             //IPAddress myGatewayObject = IPAddress.Parse(myGateWayString); //To construct your gateway IPAddress object to work with!
  158.  
  159.  
  160.  
  161.                             //setParmIP(PH[index].hostname, PH[index].IP, "255.255.255.0", gw, "147.215.1.4", "147.215.1.20", "147.215.1.136");
  162.  
  163.  
  164.  
  165.  
  166.                             setParmIP(PH[index].hostname, PH[index].IP, "255.255.255.0", gw , "147.215.1.4","147.215.1.20", "147.215.1.136");
  167.  
  168.  
  169.  
  170.  
  171.                             Console.ReadKey();
  172.                         }
  173.                     }
  174.                 }
  175.             }
  176.         }
  177.  
  178.  
  179.  
  180.         // Configue NIC
  181.  
  182.         public static void setParmIP(string ComputerName, string IPAddress, string SubnetMask, string Gateway, string DNS_primary, string DNS_secondary, string WINS_Server)
  183.         {
  184.  
  185.             ManagementClass objMC = new ManagementClass(
  186.                 "Win32_NetworkAdapterConfiguration");
  187.             ManagementObjectCollection objMOC = objMC.GetInstances();
  188.  
  189.         foreach (ManagementObject objMO in objMOC)
  190.                 {
  191.  
  192.                     if (!(bool)objMO["IPEnabled"])
  193.                         continue;
  194.  
  195.  
  196.  
  197.                     try
  198.                     {
  199.                         ManagementBaseObject objNewIP = null;
  200.                         ManagementBaseObject objSetIP = null;
  201.                         ManagementBaseObject objNewGate = null;
  202.                         ManagementBaseObject objNewDNS = null;
  203.                         ManagementBaseObject objNewWINS = null;
  204.  
  205.  
  206.                         objNewIP = objMO.GetMethodParameters("EnableStatic");
  207.                         objNewGate = objMO.GetMethodParameters("SetGateways");
  208.  
  209.  
  210.  
  211.  
  212.                         //Set DefaultGateway
  213.                         objNewGate["DefaultIPGateway"] = new string[] { Gateway };
  214.                         objNewGate["GatewayCostMetric"] = new int[] { 1 };
  215.  
  216.  
  217.                         //Set IPAddress and Subnet Mask
  218.                         objNewIP["IPAddress"] = new string[] { IPAddress };
  219.  
  220.                         objNewIP["SubnetMask"] = new string[] { SubnetMask };
  221.  
  222.                         objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
  223.                         objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
  224.                         //Set DNS server
  225.                         objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
  226.                         objNewDNS["DNSServerSearchOrder"] = new string[] { DNS_primary, DNS_secondary };
  227.                         objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);
  228.  
  229.                         //Set WINS server
  230.                         objNewWINS = objMO.GetMethodParameters("SetWINSServer");
  231.                         //objNewWINS["WINSPrimaryServer"] = new string[] {WINS_Server}; // not working
  232.                         objNewWINS.SetPropertyValue("WINSPrimaryServer", WINS_Server);
  233.                         objNewWINS.SetPropertyValue("WINSSecondaryServer", "");
  234.  
  235.                         objSetIP = objMO.InvokeMethod("SetWINSServer", objNewWINS, null);
  236.  
  237.                         // Set hostname to do
  238.                         string compName = System.Windows.Forms.SystemInformation.ComputerName.ToString();
  239.                         WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_ComputerSystem");
  240.                         ManagementObjectSearcher search = new ManagementObjectSearcher(query);
  241.                         object[] name = { ComputerName };
  242.                         foreach (ManagementObject mo in search.Get())
  243.                         {
  244.                             mo.InvokeMethod("Rename", name);
  245.                         }
  246.  
  247.  
  248.            Console.WriteLine(
  249.                            "Updated IPAddress, SubnetMask , Default Gateway ,DNS, Wins and Hostname !");
  250.  
  251.  
  252.                     }
  253.                     catch (Exception ex)
  254.                     {
  255.                         Console.WriteLine("Unable to Set IP : " + ex.Message);
  256.  
  257.                         //read the ASCII value of the char typed and cast it to a char value
  258.                         //   char ch = (char)Console.Read();
  259.  
  260.                         // read the ASCII value of the char typed
  261.  
  262.                         //           int asciiCode = Console.Read();
  263.  
  264.                         // read the input data until a return or new line is read
  265.                         // this allows the user to type away until they press enter/return
  266.                         // this method will return you information one line at a time... hence the name! :)
  267.  
  268.                     }
  269.  
  270.                 }
  271.             }
  272.         }
  273.     }
  274.  
May 20 '10 #1
5 4087
ThatThatGuy
449 Recognized Expert Contributor
Windows application is an entirely different concept....
so you'll need to just write processing statements with... no Console.WriteLi ne() or Consol.ReadLine () statements

Windows services have OnStart and OnStop methods...
May 20 '10 #2
Curtis Rutland
3,256 Recognized Expert Specialist
I would suggest starting a new project in Visual Studio. One of the project types is "Windows Service". Then copy/paste the relevant code, modifying it to properly work.

Rather than just a Main() entry point, the Windows Service has an event called OnStart(). This is what is called when the service is started.

Also, as ThatThatGuy has mentioned, there is no Console for Windows Services. If you want output, you will need to write to a file/Event Log/database.
May 20 '10 #3
ThatThatGuy
449 Recognized Expert Contributor
@codingZZ
Don't try to convert it to a Windows Service....

Instead create a new project.. (as recommended by insertAlias)...

http://en.csharp-online.net/Creating_a_.NET _Windows_Servic e
May 21 '10 #4
codingZZ
2 New Member
can someone teach me how to write a method or anything to according to the code as I can't get my program to work after browsing the web for examples.
May 21 '10 #5
ThatThatGuy
449 Recognized Expert Contributor
@codingZZ
i think gave you the link for the Web service tutorial and i think that's enough for a starter

http://en.csharp-online.net/Creating...indows_Service
May 21 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

6
1277
by: ToeKnee | last post by:
I have a c# component that can be used in various executables. I need a way in the code of this component to determine if the executable that loaded it is a Windows Service -or- a Console/Windows application? i.e. within the code of this component how can I determine if the process that loaded it is a Service or App? I am looking for a C#...
1
267
by: Jonesgj | last post by:
Hi, I have an Windows application, an 'exe', which I believe I need to convert to a windows 'service'? I need to do this as the application is basically an ETL for data, and lives on our server and unfortunately our company run scripts to close down applications left running when the remote access software disconnects. The security...
2
1555
by: wayne calvert | last post by:
hello all just started learning vb.net and i'm having problem with console applications. according to the book i using when i put out the old 'Hello from Visual Basic' thing i should be able to see it followed by a line saying 'Press any key to continue'. however my console opens (i think displays my 'Hello from Visual Basic' ) then closes...
3
1411
by: John Wildes | last post by:
Hello I have a Windows Forms application that I would like to convert into a Windows Service. The application queries an SQL server for a particular set of and then exports it to a network location as a Tab Delimited Text File. I am going to add some functionality that will also upload this file to an internal FTP site. This needs to...
2
1712
by: MATT | last post by:
I am trying to create a windows service. The part I am having trouble with is writing text to a log file. I am using a very basic StreamWriter function to try to test this. I have created a very basic service app to try to test this: OnStart timer1.enabled = True OnStop
4
12705
by: maxt | last post by:
I am using Windows XP, Tomcat 5.5.17, JRE 1.5.0_08. I am in Australia. For testing localization, my Windows Region is set to English, US. The Tomcat xml's are set to their install defaults. When using the Console, tomcat5.exe, my localization files work correctly, returning the Locale, en_US in the string str. When using Windows...
3
4589
by: Jake K | last post by:
I have a multithreaded application that I now want to convert into a Windows Service. Does application.run work in a windows service? Are there things to take into consideration when creating a multithreaded windows service as opposed to a multithreaded windows forms application? E.G. namespace whatever {
0
800
by: Nayaki | last post by:
Hi, I have a code written in VB. It is a console application. I need to convert it as Windows Service application. Could anyone provide me the procedure to do this? Also please let me know whether any code changes needs to be done. Thanks in advance, Regards, Nayaki
3
3361
by: PRR | last post by:
I have a console program.. which i need to convert to a windows service... My basic requirement is that the program needs to run in background and consume as less memory n CPU time as possible..I am not a expert in threading .. my guess was to create threads n execute them to give an example : public static Thread t2; public static Thread...
5
2643
by: rcook349 | last post by:
I want to run a piece of C# code at midnight every night that opens a file, changes something in it, and saves it. Would this be a Console Application set up as some sort of job? Would it be a Windows Service? Thanks, Ron
0
7479
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7411
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...
0
7669
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. ...
0
7926
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...
0
7773
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...
0
5987
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...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3468
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...
0
722
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...

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.