跳至頁尾內容
.NET 幫助

C# 列印控制台:逐步指南

向控制台列印是 C# 程式設計的一個基本方面,它允許開發人員顯示資訊、與使用者互動以及偵錯應用程式。 在這篇全面的文章中,我們將探討在 C# 中向控制台列印的各種方法,涵蓋基本輸出、格式化和進階技巧。

基本控制台輸出

在 C# 中,向控制台列印內容最直接的方法是使用Console類別的WriteLine方法。 此方法將一行文字後面跟著一個換行符號寫入標準輸出流。

using System;

class Program
{
    public static void Main()
    {
        // Output a simple greeting message to the console
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Output a simple greeting message to the console
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}
$vbLabelText   $csharpLabel

這裡, Console.WriteLine語句向控制台輸出"Hello World, Welcome to C#!"。 Console.WriteLine方法會自動加入換行符,使後續的每個輸出都顯示在新的一行上。

Console.Write用於內聯輸出

如果要列印文字而不換行,可以使用Console類別的Write方法。 這對於以單行形式進行內聯或格式化輸出非常有用。

using System;

class Program
{
    public static void Main()
    {
        // Use Console.Write to print text inline without a newline
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Use Console.Write to print text inline without a newline
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}
$vbLabelText   $csharpLabel

在這個例子中,"Hello, "和"C#!"印在同一行上,因為Console.Write不會像上面討論的Console.WriteLine方法那樣添加換行符。

格式化輸出

C# 提供了多種格式化選項來控制資料在控制台應用程式中的顯示方式。 Console.WriteLine方法支援使用格式說明符進行複合格式設定。

using System;

class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 25;
        // Using composite formatting to print variable values
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
    }
}
using System;

class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 25;
        // Using composite formatting to print variable values
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
    }
}
$vbLabelText   $csharpLabel

這裡, {0}{1}分別是nameage值的佔位符。 這將產生格式化的輸出"姓名:John,年齡:25"。

使用字串插值

字串插值是 C# 6 中引入的一種簡潔的字串格式化方法。它允許您將表達式直接嵌入到字串字面量中。

using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        // Using string interpolation to format output
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        // Using string interpolation to format output
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
$vbLabelText   $csharpLabel

$符號表示字串插值, {}內的表達式將被求值並插入到字串中。

控制台輸出:姓名:Alice,年齡:30

顯示目前日期

在這裡,我們將探討如何使用Console.WriteLine方法將目前日期列印到控制台。 這是調試、記錄日誌或向用戶提供即時回饋的常見做法。

using System;

class Program
{
    public static void Main()
    {
        // Obtain the current date and time
        DateTime currentDate = DateTime.Now;

        // Print the current date to the console
        Console.WriteLine($"Current Date: {currentDate}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Obtain the current date and time
        DateTime currentDate = DateTime.Now;

        // Print the current date to the console
        Console.WriteLine($"Current Date: {currentDate}");
    }
}
$vbLabelText   $csharpLabel

在這個範例中,我們使用DateTime.Now屬性來取得目前日期和時間。然後使用Console.WriteLine語句將此資訊印到控制台。 最終呈現出清晰簡潔的當前日期顯示。

控制台輸入

除了輸出之外,控制台通常也用於使用者輸入。 Console.ReadLine方法可讓您讀取使用者輸入的一行文字。

using System;

class Program
{
    public static void Main(string[] args)
    {
        // Prompt the user to enter their name
        Console.Write("Enter your name: ");

        // Read input from the user
        string variable = Console.ReadLine();

        // Print a personalized greeting
        Console.WriteLine($"Hello, {variable}!");
    }
}
using System;

class Program
{
    public static void Main(string[] args)
    {
        // Prompt the user to enter their name
        Console.Write("Enter your name: ");

        // Read input from the user
        string variable = Console.ReadLine();

        // Print a personalized greeting
        Console.WriteLine($"Hello, {variable}!");
    }
}
$vbLabelText   $csharpLabel

程式會提示使用者輸入姓名,使用Console.ReadLine讀取輸入內容,然後在一行字串中列印個人化的問候語。

控制台顏色

您可以變更控制台文字的前景色和背景色,以增強視覺效果。 Console.ForegroundColorConsole.BackgroundColor屬性用於此目的。

using System;

class Program 
{
    public static void Main()
    { 
        // Set the console text color to green
        Console.ForegroundColor = ConsoleColor.Green;

        // Set the console background color to dark blue
        Console.BackgroundColor = ConsoleColor.DarkBlue;

        // Print a message with the set colors
        Console.WriteLine("Colored Console Output");

        // Reset colors to default
        Console.ResetColor();
    }
}
using System;

class Program 
{
    public static void Main()
    { 
        // Set the console text color to green
        Console.ForegroundColor = ConsoleColor.Green;

        // Set the console background color to dark blue
        Console.BackgroundColor = ConsoleColor.DarkBlue;

        // Print a message with the set colors
        Console.WriteLine("Colored Console Output");

        // Reset colors to default
        Console.ResetColor();
    }
}
$vbLabelText   $csharpLabel

此程式碼範例將前景色設為綠色,背景色設為深藍色,然後在文字列印完成後將顏色重設為預設值。

高級控制台輸出

對於更進階的場景,例如列印格式化資料、表格或進度指示器,您可以探索 NuGet 套件管理器中的ConsoleTables等第三方程式庫,或使用進階格式化技術實作自訂解決方案。

using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        // Create a new table with specified column headers
        var table = new ConsoleTable("ID", "Name", "Age");

        // Add rows to the table
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);

        // Print the table to the console
        Console.WriteLine(table);
    }
}
using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        // Create a new table with specified column headers
        var table = new ConsoleTable("ID", "Name", "Age");

        // Add rows to the table
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);

        // Print the table to the console
        Console.WriteLine(table);
    }
}
$vbLabelText   $csharpLabel

在這個例子中,我們使用ConsoleTables庫將格式化的表格列印到控制台。 這使得控制台視窗的輸出看起來更加現代、簡潔。

控制台視窗:使用ConsoleTables庫將格式化表格列印到控制台。

IronPrint:簡化 .NET 列印功能

IronPrint是由 Iron Software 開發的多功能列印庫,旨在幫助 .NET 開發人員將強大的列印功能無縫整合到他們的應用程式中。 無論您是開發 Web 應用程式、桌面應用程式還是行動解決方案,IronPrint 都能確保在各種 .NET 平台上提供無縫且可部署的列印體驗。

IronPrint for .NET:C# 列印庫

IronPrint 的主要特點

1. 跨平台支持

IronPrint 與多種環境相容,確保您的應用程式可以在不同平台上利用其列印功能,包括:

  • Windows(7+,Server 2016+)
  • macOS(10+)
  • iOS(11+)
  • Android API 21+(v5"棒棒糖")

2. .NET 版本支持

該程式庫支援多種 .NET 版本,使其能夠靈活應用於各種專案:

  • 支援 .NET 8、7、6、5 和 Core 3.1+
  • .NET Framework (4.6.2+)

3. 專案類型支持

IronPrint 可滿足 .NET 生態系中不同類型的專案需求:

  • 行動端(Xamarin、MAUI 和 Avalonia)
  • 桌面(WPF、MAUI 和 Windows Avalonia)
  • 控制台(應用程式和庫)

4. 廣泛的格式支持

IronPrint 支援多種文件格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP。這種靈活性使其成為處理不同類型文件的開發人員的理想選擇。

5. 可自訂的列印設定

利用 IronPrint 的自訂設置,打造專屬您的列印體驗。 調整 DPI,指定份數,設定紙張方向(縱向或橫向)等等。 該庫使開發人員能夠微調列印配置,以滿足其應用程式的需求。

安裝流程

IronPrint 的入門過程非常簡單。 請依照以下步驟安裝庫:

  1. 使用 NuGet 套件管理器安裝 IronPrint 套件:

    # Install IronPrint via NuGet Package Manager
    Install-Package IronPrint
    # Install IronPrint via NuGet Package Manager
    Install-Package IronPrint
    SHELL

    或者,直接從IronPrint NuGet 官方網站或 NuGet 解決方案套件管理器下載該套件。

    使用 NuGet 套件管理器安裝 IronPrint,方法是在 NuGet 套件管理器的搜尋欄中搜尋ironprint,然後選擇項目並點擊安裝按鈕。

  2. 安裝完成後,在 C# 程式碼頂部新增以下語句即可開始使用 IronPrint:

    using IronPrint;
    using IronPrint;
    $vbLabelText   $csharpLabel
  3. 透過將許可證金鑰值指派給License類別的LicenseKey屬性來應用有效的已購買授權或試用金鑰:

    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
    $vbLabelText   $csharpLabel

程式碼範例

1. 列印文檔

使用 IronPrint 可以簡化文件列印流程。 只需將檔案路徑傳遞給Print方法即可:

using IronPrint;

// Print the document
Printer.Print("newDoc.pdf");
using IronPrint;

// Print the document
Printer.Print("newDoc.pdf");
$vbLabelText   $csharpLabel

2. 帶對話框的列印

若要在列印前顯示列印對話框,請使用ShowPrintDialog方法:

using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
$vbLabelText   $csharpLabel

3. 自訂列印設定

透過使用以下程式碼實例化PrintSettings類,以程式設計方式配置列印設定:

using IronPrint;

// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;

// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);
using IronPrint;

// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;

// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);
$vbLabelText   $csharpLabel

許可與支持

IronPrint 雖然是付費庫,但提供免費試用許可證。 使用 IronPrint 的許可頁面申請永久許可。 如需更多支援和諮詢,請聯絡Iron Software 團隊

結論

對於 C# 開發人員來說,向控制台輸出資訊是一項基本技能。 無論是基本的文字輸出、格式化字串、使用者輸入,還是進階控制台操作,了解各種可用技術都能幫助您建立強大且使用者友好的控制台應用程式。 嘗試這些方法,並根據您特定項目的需求進行調整。

IronPrint是一款功能強大的 .NET 列印庫,以其準確性、易用性和速度而聞名。 有關 IronPrint 的更多信息,並探索 IronPrint 提供的全部功能和程式碼範例,請造訪官方文件API 參考頁面。

IronPrint 還提供免費試用,以便在商業環境中測試其全部潛力。 但是,試用期結束後,您需要購買許可證。 其 Lite 套餐起價為$799 。 從這裡下載庫文件並試用一下!

常見問題解答

C#中列印至控制台的基本方法有哪些?

C# 中向控制台列印的基本方法包括Console.WriteLine用於輸出帶換行符的文字)和Console.Write用於輸出不帶換行符的行內文字)。

如何在 C# 中使用字串插值進行控制台輸出?

C# 中的字串插值可讓您使用$符號將變數直接包含在字串中,從而更容易使用動態內容格式化控制台輸出。

C#中實作控制台輸出有哪些進階技巧?

進階技巧包括使用複合格式或ConsoleTables等函式庫進行結構化資料輸出,以及使用Console.ForegroundColorConsole.BackgroundColor更改文字顏色。

C# 開發人員如何從控制台讀取使用者輸入?

開發者可以使用Console.ReadLine方法從控制台捕獲使用者輸入,該方法會讀取使用者輸入的一行文字。

在C#中,有哪些方法可以改變控制台文字顏色?

您可以透過在將訊息列印到控制台之前設定Console.ForegroundColorConsole.BackgroundColor屬性來變更控制台文字顏色。

IronPrint 如何增強 .NET 的列印功能?

IronPrint 透過為各種平台和文件格式提供強大的功能來增強 .NET 列印,它還包括可自訂的列印設置,例如 DPI 和紙張方向。

該列印庫支援哪些平台和 .NET 版本?

該程式庫支援 Windows、macOS、iOS、Android,並且相容於 .NET 8、7、6、5、Core 3.1+ 和 .NET Framework 4.6.2+。

如何使用 NuGet 安裝 IronPrint 函式庫?

您可以使用 NuGet 套件管理員透過指令Install-Package IronPrint安裝 IronPrint,也可以從 IronPrint NuGet 網站下載。

如何在 C# 中使用控制台顯示目前日期?

要在 C# 中顯示目前日期,請使用DateTime.Now取得目前日期和時間,然後使用Console.WriteLine列印它。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。