รัน C# Script (.csx) บน Visual Studio Code

wk
2 min readMay 25, 2017

--

โปรแกรม Visual Studio Code (vscode) ได้อินทิเกรทความสามารถในการเขียนสคริปท์ C# (ไฟล์ .csx) มาพร้อมกับเอ็กเทนชั่น C# for Visual Studio Code มี syntax highlight, syntax checker แต่ยังไม่มีสามารถรันสคริปท์ได้ เนื่องจากไม่มีสคริปท์รันเนอร์อินทิเกรทมาด้วย

สคริปท์รันเนอร์ ที่สามารถคอมไพล์และรันไฟล์ .csx ในตอนนี้มีหลายตัว เช่น

ตัวอย่างนี้จะแนะนำการใช้ csi.exe บน Windows และ csharp บน mac OS และเพื่อความสะดวกในการรันโปรแกรม เราจะใช้ Save and Run ซึ่งเป็นเอ็กเทนชั่นของ vscode ร่วมด้วย โดยทุกครั้งที่บันทึกไฟล์โปรแกรมทำงานทันที โดยไม่ต้องสั่ง execute ผ่านคอมมานด์ไลน์

ติดตั้ง Save and Run

  1. เปิด Visual Studio Code
  2. กด Ctrl + Shift + p เลือก Install extensions
  3. Search คำว่า Save and Run
  4. เลือก Install

คอนฟิก Save and Run บน Windows

บน Windows จะใช้ csi.exe ซึ่งเป็นสคริปท์รันเนอร์ที่มาพร้อมกับ Visual Studio ปกติจะอยู่ในโฟลเดอร์ MSBuild

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\csi.exe

เปิด Workspace settings (Ctrl + Shift + p พิมพ์ Open Workspace Settings) แล้วแก้ไขไฟล์ settings.json โดยเพิ่มพาธ csi.exe ในช่อง cmd ตามตัวอย่างด้านล่าง

{
"saveAndRun": {
"commands": [
{
"match": "\\.csx$",
"cmd": "& \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\MSBuild\\15.0\\Bin\\Roslyn\\csi.exe\" ${relativeFile}"
}]
}
}

คอนฟิก Save and Run บน mac OS

ใช้โปรแกรม csharp ที่มาพร้อมกัน mono 5.0 โดยเปลี่ยนคอนฟิกใน Workspace settings จาก csi.exe (Windows) เป็น csharp แทน

{
"saveAndRun": {
"commands": [
{
"match": "\\.csx$",
"cmd": "csharp ${relativeFile}"
}]
}
}

เขียนและรันสคริปท์

  1. สร้างไฟล์ Hello.csx
  2. พิมพ์ Console.WriteLine(“Hello, world!”);
  3. บันทึก
  4. Save and Run จะทำงานโดยไปเรียกสคริปท์รันเนอร์ที่คอนฟิกไว้ ผลลัพธ์จะแสดงในเทอร์มินัลด้านล่างของโปรแกรม

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response