Run C# code on linux terminal

Viewed 100012

How can I execute a C# code on a linux terminal as a shell script.

I have this sample code:

public string Check(string _IPaddress,string _Port, int _SmsID)
{
ClassGlobal._client = new TcpClient(_IPaddress, Convert.ToInt32(_Port));
ClassGlobal.SMSID = _SmsID;
string _result = SendToCAS(_IPaddress, _Port, _SmsID );
if (_result != "") return (_result);
string _acoknoledgement = GetFromCAS();
return _acoknoledgement;
}

When I run a shell bash I use #!/bin/bash. There is how to do the same with C#?

6 Answers

The #! (hashbang) tag is used to tell the shell which interpreter to use so that your perl, php, bash, sh, etc. scripts will run right.

But C# is not a scripting language, it is intended to be compiled into an executable format. You need to install at least a compiler and runtime if you want to use C#, and preferably an IDE (Integrated Development Environment) to help you develop and debug your applications.

Install Mono for the compiler and runtime, then MonoDevelop for the IDE.

After installing mono you can use csharp hello.cs. Starting with Mono 2.10, you can also use the shebang like this:

#!/usr/bin/csharp
Console.WriteLine ("Hello, World");

If you need assemblies, you can load them e.g. with the line LoadAssembly("System.IO.Compression") inside your script.

Reference: man csharp.

You can't execute C# like a script, you have to compile it first. For that, you could install mono.

You can then compile your program with mcs and execute it with mono.

First, you have to install mono

sudo apt install mono-complete

Commands to execute

mcs -out:$1.exe $1.cs
mono $1.exe 

You can add these in a script to make the process easier. Create a shell sript and add the parent directory to the PATH environment variable. Example: export PATH=$PATH":$HOME/Desktop/customcommands"

And also give execute permission to the script file. Shell script:

#!/bin/sh
dpkg -s mono-complete > /dev/null

if [ $? -eq 0 ]; then
    echo 
else 
    read -p "Package mono-complete not installed. Press y to install or n to quit." response
    yes="y"
    if [ "$response" = "y" ];
    then
         sudo apt install mono-complete
         echo " "
         echo " "
    fi  
fi
mcs -out:$1.exe $1.cs
mono $1.exe
Related