การรัน C# บน Linux: ทุกยุค
1. Mono (Legacy/Cross-Platform Framework)
Mono เป็น Open-source Implementation ของ .NET Framework ทำงานบน Linux, macOS, Windows
- รองรับ Windows Forms, ASP.NET, ADO.NET, LINQ
- Compiler:
mcs(Mono C# Compiler) - Runtime:
monocommand - Status: Maintenance Mode, แทนที่ด้วย .NET Core/.NET 5+
2. .NET Core / .NET 5+ (Modern, Recommended)
Cross-platform, High-performance, Open-source, Microsoft Supported
- SDK:
dotnetCLI - Runtime:
dotnet run,dotnet exec - Self-contained Deployment: ไม่ต้องติดตั้ง Runtime
ติดตั้ง .NET บน Linux (Ubuntu/Debian)
# Microsoft Package Repository
wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
# Install SDK (รวม Runtime)
sudo apt-get install -y dotnet-sdk-8.0
# Verify
dotnet --version
# 8.0.xxx
สร้างและรัน Project (.NET CLI)
# สร้าง Console App
dotnet new console -n MyApp
cd MyApp
# Run (Compile + Execute)
dotnet run
# Build Only
dotnet build
# Release Build
dotnet build -c Release
# Publish (Self-contained)
dotnet publish -c Release -r linux-x64 --self-contained true
# Output: ./bin/Release/net8.0/linux-x64/publish/MyApp (Executable Binary)
Hello World บน Linux
// Program.cs
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("C# running on Linux!");
Console.WriteLine($"OS: {Environment.OSVersion}");
Console.WriteLine($"Architecture: {Environment.Is64BitOperatingSystem}");
Console.WriteLine($".NET Version: {Environment.Version}");
}
}
}
Output
C# running on Linux! OS: Unix 5.15.0-91-generic Architecture: True .NET Version: 8.0.0
Mono (ถ้าจำเป็นต้องใช้ Legacy)
# Ubuntu
sudo apt-get install mono-complete
# Compile
mcs Program.cs
# Output: Program.exe
# Run
mono Program.exe
# หรือ
./Program.exe (ถ้ามี binfmt_misc configured)
GUI บน Linux
| Framework | Linux Support | หมายเหตุ |
|---|---|---|
| Windows Forms | ⚠️ Limited (Mono) | ไม่แนะนำสำหรับ Production Linux |
| WPF | ❌ ไม่รองรับ | Windows Only |
| MAUI | ⚠️ Experimental | Linux Community Port |
| Avalonia | ✅ Full Support | Cross-platform XAML UI (Recommended) |
| Blazor Hybrid | ✅ WebView2/GTK | Web Tech ใน Desktop |
| Electron.NET | ✅ | Electron + ASP.NET Core |