user2837314
user2837314

Reputation: 41

How to run a C# code in batch file?

I have a C# code to display audit report of computer. But I need to integrate it in batch file. Kindly Help

Upvotes: 1

Views: 425

Answers (2)

npocmaka
npocmaka

Reputation: 57252

Save this as .bat and test it

//>nul 2>nul||@goto :batch
/****** Batch code *******

:batch
@echo off
setlocal

:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set csc=%frm%%netver%\csc.exe
:: csc.exe found

call %csc% /nologo /out:"%~n0.exe" "%~dpsfnx0" 
%~n0.exe %*
:::::
 echo this was echoed from the batch
::::
endlocal
pause
exit /b 0

******* end of batch code *****/
// c# code
public class Hello
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, C# World!");
   }
}

More info here

Upvotes: 1

Serpardum
Serpardum

Reputation: 26

Write your C# program and compile it as an exe program. In your batch file simply call it. If you need some value from the program use the return statement to return an integer.

Note: all code is untested, pseudo code and given for examples only. Syntax errors abound.

If you need to pass parameters to your C# program simply pass them when you call the program.

For errorlevel coding see here: http://www.robvanderwoude.com/errorlevel.php For variable coding see here: http://www.tech-recipes.com/rx/630/using-variables-in-windows-batch-files/ For command line parameters see here: How do I pass command line parameters to a batch file?

@echo off
set Parm2=Parameter2
MyCSharpProgram.exe %1 %Parm2% Parameter3
if (errorlevel 2) GOTO label2
if (errorlevel 1) GOTO label1
goto end

label1:
rem do something here based an returning a value of 1
GOTO end

label2:
rem do something here based on returning a value of 2
GOTO end
rem yeah, above line not needed but I always add it to document what I'm doing.

:end
echo Thank you for your support.

Upvotes: 0

Related Questions