How do you convert a console application to a windows service.Any recommendations ? The following code is below - using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Runtime.InteropServices;
-
-
using System.Management;
-
using System.IO;
-
using System.Text.RegularExpressions;
-
-
public struct ParamHost
-
{
-
public string MAC, hostname,IP;
-
-
public ParamHost(string MAC, string hostname, string IP)
-
{
-
this.MAC = MAC;
-
this.hostname = hostname;
-
-
this.IP = IP;
-
}
-
}
-
-
-
namespace NetworkCardConfig
-
{
-
class Program
-
{
-
-
-
-
static void Main(string[] args)
-
{
-
// Open file MAC.TXT
-
// read from file or write to file
-
System.IO.FileStream myStream = new FileStream("C:\\MAC.txt", FileMode.Open);
-
-
System.IO.StreamReader myStreamReader = new StreamReader(myStream);
-
-
string fileContent = myStreamReader.ReadToEnd();
-
-
myStreamReader.Close();
-
-
string[] Lines = fileContent.Split('\n');
-
-
String[] Field;
-
-
ParamHost[] PH;
-
-
-
PH = new ParamHost[Lines.Length]; // to do
-
-
int PH_Number = 0;
-
-
-
foreach (string Line in Lines)
-
{
-
-
if (Line != "" && Line != "\r")
-
{
-
Console.WriteLine("line :" + Line);
-
-
Field = Line.Split(';');
-
-
Console.WriteLine("MAC {0}; hostname{1}; IP: {2}", Field[0], Field[1], Field[2]);
-
-
PH[PH_Number].MAC = Field[0];
-
PH[PH_Number].hostname = Field[1];
-
PH[PH_Number].IP = Field[2];
-
-
/*
-
for (int i = 0; i < Field.Length; i++)
-
{
-
Console.WriteLine(Field[i]);
-
}*/
-
PH_Number++;
-
-
-
//foreach (String i in Field)
-
//{
-
-
// Console.WriteLine(Field[i]);
-
-
-
//}
-
//PH_Number++;
-
-
-
-
-
-
-
-
}
-
-
// Console.WriteLine("{0}", fileContent);
-
-
myStreamReader.Close();
-
-
//Console.WriteLine(PH[0].MAC);
-
-
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
-
-
-
ManagementObjectCollection objMOC = objMC.GetInstances();
-
-
-
string gw;
-
string myIpString;
-
char[] delim;
-
string[] myIpArray;
-
string myGateWayString;
-
-
-
-
foreach (ManagementObject objMO in objMOC)
-
{
-
-
if (!(bool)objMO["ipEnabled"])
-
continue;
-
//Console.WriteLine(objMO["Caption"] + "," + objMO["ServiceName"] + "," + objMO["MACAddress"]);
-
-
string MAC_card = objMO["MACAddress"].ToString();
-
-
for (int index = 0; index < PH_Number; index++)
-
{
-
string MAC_File = PH[index].MAC.ToString();
-
-
//Console.WriteLine("jkjkjk :" + MAC_card + MAC_File);
-
-
if (MAC_card.Equals(MAC_File))
-
{
-
Console.WriteLine("good card to configure ! ! " + MAC_File);
-
Console.WriteLine("hostname " + PH[index].hostname);
-
Console.WriteLine("IP " + PH[index].IP);
-
// Set nic parameters
-
// to do
-
-
//string gw = PH[index].IP;
-
-
-
gw = PH[index].IP;
-
-
//PH[index].IP = x.y.z.w -> gw= x.y.z.1
-
-
// to do gw = .1
-
-
-
-
//assuming myLocalIP is the IPAddress object you are using from the IPAddress array you will have been playing with before...
-
myIpString = gw.ToString(); //to return nice "255.255.255.255" notation to work with
-
delim = new char[1]; //set the delimiter you want to split your IP string by - so '.'
-
delim[0] = '.'; //set the delimiter you want to split your IP string by - so '.'
-
myIpArray = myIpString.Split(delim); //actually split the IP up
-
myIpArray[3] = "1";
-
myGateWayString = myIpArray[0] + "." + myIpArray[1] + "." + myIpArray[2] + "." + myIpArray[3]; //to reconstruct your gateway string
-
//IPAddress myGatewayObject = IPAddress.Parse(myGateWayString); //To construct your gateway IPAddress object to work with!
-
-
-
-
//setParmIP(PH[index].hostname, PH[index].IP, "255.255.255.0", gw, "147.215.1.4", "147.215.1.20", "147.215.1.136");
-
-
-
-
-
setParmIP(PH[index].hostname, PH[index].IP, "255.255.255.0", gw , "147.215.1.4","147.215.1.20", "147.215.1.136");
-
-
-
-
-
Console.ReadKey();
-
}
-
}
-
}
-
}
-
}
-
-
-
-
// Configue NIC
-
-
public static void setParmIP(string ComputerName, string IPAddress, string SubnetMask, string Gateway, string DNS_primary, string DNS_secondary, string WINS_Server)
-
{
-
-
ManagementClass objMC = new ManagementClass(
-
"Win32_NetworkAdapterConfiguration");
-
ManagementObjectCollection objMOC = objMC.GetInstances();
-
-
foreach (ManagementObject objMO in objMOC)
-
{
-
-
if (!(bool)objMO["IPEnabled"])
-
continue;
-
-
-
-
try
-
{
-
ManagementBaseObject objNewIP = null;
-
ManagementBaseObject objSetIP = null;
-
ManagementBaseObject objNewGate = null;
-
ManagementBaseObject objNewDNS = null;
-
ManagementBaseObject objNewWINS = null;
-
-
-
objNewIP = objMO.GetMethodParameters("EnableStatic");
-
objNewGate = objMO.GetMethodParameters("SetGateways");
-
-
-
-
-
//Set DefaultGateway
-
objNewGate["DefaultIPGateway"] = new string[] { Gateway };
-
objNewGate["GatewayCostMetric"] = new int[] { 1 };
-
-
-
//Set IPAddress and Subnet Mask
-
objNewIP["IPAddress"] = new string[] { IPAddress };
-
-
objNewIP["SubnetMask"] = new string[] { SubnetMask };
-
-
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
-
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
-
//Set DNS server
-
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
-
objNewDNS["DNSServerSearchOrder"] = new string[] { DNS_primary, DNS_secondary };
-
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);
-
-
//Set WINS server
-
objNewWINS = objMO.GetMethodParameters("SetWINSServer");
-
//objNewWINS["WINSPrimaryServer"] = new string[] {WINS_Server}; // not working
-
objNewWINS.SetPropertyValue("WINSPrimaryServer", WINS_Server);
-
objNewWINS.SetPropertyValue("WINSSecondaryServer", "");
-
-
objSetIP = objMO.InvokeMethod("SetWINSServer", objNewWINS, null);
-
-
// Set hostname to do
-
string compName = System.Windows.Forms.SystemInformation.ComputerName.ToString();
-
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_ComputerSystem");
-
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
-
object[] name = { ComputerName };
-
foreach (ManagementObject mo in search.Get())
-
{
-
mo.InvokeMethod("Rename", name);
-
}
-
-
-
Console.WriteLine(
-
"Updated IPAddress, SubnetMask , Default Gateway ,DNS, Wins and Hostname !");
-
-
-
}
-
catch (Exception ex)
-
{
-
Console.WriteLine("Unable to Set IP : " + ex.Message);
-
-
//read the ASCII value of the char typed and cast it to a char value
-
// char ch = (char)Console.Read();
-
-
// read the ASCII value of the char typed
-
-
// int asciiCode = Console.Read();
-
-
// read the input data until a return or new line is read
-
// this allows the user to type away until they press enter/return
-
// this method will return you information one line at a time... hence the name! :)
-
-
}
-
-
}
-
}
-
}
-
}
-
5 4087
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...
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.
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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#...
|
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...
|
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...
|
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...
|
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
| |
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...
|
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
{
|
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
|
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...
|
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
|
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...
| |
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...
|
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. ...
|
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...
|
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...
|
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...
|
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...
| |
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...
|
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...
| |