跳過到頁腳內容
.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 庫將格式化的表格列印到控制台。 這使得控制台視窗的輸出看起來更加現代、簡潔。

Console Window: Printed a formatted table to the console using ConsoleTables library.

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解決方案套件管理器下載該套件。

    Install IronPrint using NuGet Package Manager by searching ironprint in the search bar of NuGet Package Manager, then select the project and click on the Install button.

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

    using IronPrint;
    using IronPrint;
    $vbLabelText   $csharpLabel
  3. 透過將許可證金鑰值指派給 @@--CODE-479--CODE-478--CODE-479 類的 @@--CODE-478--CODE-479 屬性,套用有效的已購買授權或試用金鑰:

    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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我