1 Replies - 48797 Views - Last Post: 10 September 2007 - 04:41 PM Rate Topic: -----

#1 Sim_270  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 27-August 07

How to call/execute Batch File from .Net Windows Service

Posted 10 September 2007 - 06:16 AM

I Have one batch file.I want to run that batch file once the System is started .How can I call/execute Batch File from .Net Windows Service?
Is This A Good Question/Topic? 0
  • +

#17 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1639
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How to call/execute Batch File from .Net Windows Service

Posted 10 September 2007 - 04:41 PM

Put this function in your Windows Service (I take it you created the service and have access to its code), then call it when the service starts. In this function theres a line that reads batchExecute.Start("Path to your batch file here"), replace "Path to your batch file here" with the actual path to your batch file.

In this function it will execute your batch file (without showing a command window), then check its ExitCode and return a 0 (for successful) or 1 (for failed)

Public Shared Function ProcessBatchFile() As Integer
	   'Create a variable to hold the value you wish
	   'to return to your calling method
		Dim batchSuccessful As Integer
		'Create a new Process(), I just happen
	   'to name this "YourName"
	   Dim batchExecute As New Process()

		'This is a method that you can use to set
		'properties for your new Process()
		 Dim batchExecuteInfo As New ProcessStartInfo()

	   'Tell the program to not use the built-in Shell provided
	   'with the OS, wew ant to start it ourselved
	   batchExecuteInfo.UseShellExecute = False

	   'Tell the process to not open a Console window
	   batchExecuteInfo.CreateNoWindow = True

		'Set your process info here
		 batchExecute.StartInfo = batchExecuteInfo
		'Start your Process(), this will start the
		'command line and send your command
		batchExecute.Start("Path to your batch file here")

		'Set the period of time to wait for the associated
		'process to exit, and blocks the current thread
		'until the time has elapsed or the
		'process has exited
		batchExecute.WaitForExit(15000)

		'Create a variable and assign it the value
		'of your processes exit code
		Dim Exit As Integer = batchExecute.ExitCode

		'Check if the process has completed
		'and return a status of 0 (succeeded). If not
		'then we want to kill the process
	   If Exit > 0 And Not batchExecute.HasExited Then
			'Here you can assign a value to a variable
			'to return to your calling method
			batchSuccessful = 1
			batchExecute.Kill
	   Else
			  'Do something here and
			   'assign your successful variable a 0
			   batchSuccessful = 0
	   End If
	   'Return the value (1 or 0) to
	   'your calling method
	   Return batchSuccessful
End Function



Hope this helps :)
Was This Post Helpful? 1

Page 1 of 1